日経BP社から出ている
.NET 6 プログラミング入門 の 4.4 WebAPI をなぞってみました。
プロジェクトの作成
dotnet new webapi --name BookApi
cd BookApi
mkdir Models
rm WeatherForecast.cs
rm Controllers/WeatherForecastController.cs
フォルダー構造
$ tree -L 1
.
├── BookApi.csproj
├── Controllers
├── Models
├── Program.cs
├── Properties
├── appsettings.Development.json
├── appsettings.json
├── bin
└── obj
Models/Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#nullable disable
namespace WebApi.Models
{
public class Book
{
public string Id {get; set;}
public int Khm {get; set;}
public string Title {get; set;}
public string Deutsch {get; set;}
}
}
Controllers/BooksControllers.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi.Models;
namespace WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BooksController: ControllerBase
{
List<Book> books = new List<Book>()
{
new Book {Id="s047", Title="白雪姫",
Deutsch = "Schneewittchen",Khm = 53},
new Book {Id="s031", Title="ヘンゼルとグレーテル",
Deutsch = "Hänsel und Gretel",Khm = 15},
new Book {Id="s004", Title="おいしいおかゆ",
Deutsch = "Der süße Brei",Khm = 103},
};
[HttpGet]
public IEnumerable<Book> Get()
{
return this.books;
}
[HttpGet("{id}")]
public Book? Get(string id)
{
return this.books.FirstOrDefault(t => t.Id == id);
}
}
}
設定ファイル
appsettings.json
{
"urls": "http://*:5000;https://*:5001",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
appsettings.Development.json
{
"urls": "http://*:5000;https://*:5001",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
サーバーの起動
dotnet run
$ dotnet run
ビルドしています...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://[::]:5000
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://[::]:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /home/uchida/tmp/dotnet/webapi/BookApi/
クライアントでアクセス
http --verify=no https://localhost:5001/api/Books
http --verify=no https://localhost:5001/api/Books/s047
curl -k -X 'GET' 'https://localhost:5001/api/Books' -H 'accept: text/json'
curl -k -X 'GET' 'https://localhost:5001/api/Books/s047' -H 'accept: text/json'