13
15

More than 3 years have passed since last update.

ASP.NET Core Web API で CRUD & Swagger/OpenAPI でテスト

Last updated at Posted at 2019-04-10

はじめに

前回 ASP.NET Core Web API で Entity Framework Core を使って SQL Server から単一テーブルのデータを取得する API を作ったので、今回は他の CRUD も作っていきたいと思います。動作確認しやすいように、Swagger/OpenAPI も導入します。

Swagger/OpenAPI 導入

では Swagger/OpenAPI を導入していきましょう。MS のドキュメントでは2種類のライブラリが紹介されてますが、今回は開発が活発そうな NSwag の方を使います。

パッケージマネージャーコンソールから以下のコマンドを実行。

> Install-Package NSwag.AspNetCore

Startup.cs で NSwag を有効化。(OpenAPI 3.0)

Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SimpleWebApi.Data;
using NSwag.AspNetCore; //追加

namespace SimpleWebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<BookContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddOpenApiDocument(); //追加
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseOpenApi(); //追加
            app.UseSwaggerUi3(); //追加

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

/swagger にアクセスして API の一覧(まだ1個しかないけど)が表示されることを確認。
image.png

これで UI から簡単に API のテストができるようになったので、CRUD API を順番に作っていきます。

GET(単一リソース)

前回はテーブルのレコードすべてを返す API を作ったので、今回は特定のレコードのみ返す API を作ります。

Controllers/BooksController.cs
using System.Collections.Generic;
using System.Linq; //追加
using Microsoft.AspNetCore.Mvc;
using SimpleWebApi.Data;
using SimpleWebApi.Entities;

namespace SimpleWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        //省略//

        //追加//
        [HttpGet("{id}")]
        public ActionResult<Book> Get(int id)
        {
            var book = context.Books.FirstOrDefault(b => b.BookId.Equals(id));
            return book;
        }
    }
}

Swagger UI でテスト実行。

image.png

Create(新規作成)

新しいレコードを追加するPOST メソッドを追加します。

Controllers/BooksController.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using SimpleWebApi.Data;
using SimpleWebApi.Entities;

namespace SimpleWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        //省略//

        //追加//
        [HttpPost]
        public ActionResult<Book> Create(Book book)
        {
            context.Books.Add(book);
            context.SaveChanges();
            return CreatedAtAction(nameof(Get), new { id = book.BookId }, book);
        }
    }
}

Swagger UI でテスト実行。

image.png
image.png

bookId は 0 にするか、リクエストボディに含めずに実行すればちゃんと連番で ID を生成してくれます。

Update(更新)

レコードを更新する PUT メソッドを追加します。

Controllers/BooksController.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; //追加
using SimpleWebApi.Data;
using SimpleWebApi.Entities;

namespace SimpleWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        //省略//

        //追加//
        [HttpPut]
        public IActionResult Update(Book book)
        {
            context.Entry(book).State = EntityState.Modified;
            context.SaveChanges();
            return NoContent();
        }
    }
}

Swagger UI でテスト実行。

image.png

Get でちゃんと更新されていることを確認。
image.png

DELETE(削除)

レコードを削除する DELETE メソッドを追加します。

Controllers/BooksController.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SimpleWebApi.Data;
using SimpleWebApi.Entities;

namespace SimpleWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        //省略//

        //追加//
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var book = context.Books.FirstOrDefault(b => b.BookId.Equals(id));

            context.Books.Remove(book);
            context.SaveChanges();

            return NoContent();
        }
    }
}

Swagger UI でテスト実行。
image.png

Get でちゃんと削除されていることを確認。
image.png

ソースコード

13
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15