かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

モバイルアプリなどの練習用WebAPIを作成しました

モバイルアプリやUWPの練習でたたける簡単なAPIがほしいかも?ということで作ってAzureに置いてみました。一応認証のかかったシンプルなAPIです。

OAuth2で、ユーザー名admin、パスワードp@ssw0rdでトークンが取得できます。 Web APIは以下のような感じです。

ルート:https://okazukisampleapi.azurewebsites.net/

  • GET
    • api/People?page=数字
      • 1ページ50件でデータを返す。pageを省略した場合は最初のページのデータを返す。
    • api/People/数字
      • 数字で指定したIDのデータを1件取得する
  • PUT
    • api/People/数字
      • BODYに渡した内容でデータを更新する
  • POST
    • api/People
      • BODYに渡した内容でデータを作成する
  • DELETE
    • api/People/数字
      • 数字で指定したIDのデータを削除する

JSONは基本的に以下のデータを返します。

1件のデータを返す系

{"id":2,"name":"okazuki","birthday":"2016-09-26T12:34:05.9874877+00:00"}

複数のデータを返す系

[{"id":1,"name":"tanaka","birthday":"2016-09-26T12:32:46.1740543+00:00"},{"id":2,"name":"okazuki","birthday":"2016-09-26T12:34:05.9874877+00:00"}]

以下のようなC#のコードで認証通してAPIを呼ぶことができます。

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri("https://okazukisampleapi.azurewebsites.net/");

            var authContent = new StringContent("grant_type=password&username=admin&password=p@ssw0rd");
            authContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            var authRes = client.PostAsync("/Token", authContent).Result;

            authRes.EnsureSuccessStatusCode();

            var token = JsonConvert.DeserializeObject<AuthResult>(authRes.Content.ReadAsStringAsync().Result).AccessToken;
            Console.WriteLine(token);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var p = new Person
            {
                Name = "okazuki",
                Birthday = DateTimeOffset.UtcNow,
            };

            var postContent = new StringContent(JsonConvert.SerializeObject(p));
            postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var postRes = client.PostAsync("api/People", postContent).Result;
            postRes.EnsureSuccessStatusCode();

            Console.WriteLine(postRes.Content.ReadAsStringAsync().Result);

            var getRes = client.GetAsync("api/People").Result;
            getRes.EnsureSuccessStatusCode();
            Console.WriteLine(getRes.Content.ReadAsStringAsync().Result);
        }
    }

    class AuthResult
    {
        [JsonProperty(PropertyName = "access_token")]
        public string AccessToken { get; set; }
    }

    class Person
    {
        [JsonProperty(PropertyName = "id")]
        public int Id { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
        [JsonProperty(PropertyName = "birthday")]
        public DateTimeOffset Birthday { get; set; }
    }
}

とりあえず無償プランでDBも月500円くらいなんで放置しておこうと思います。

XamarinとかでAPIたたくアプリの練習などにどうぞ。

サーバー側ソース

github.com