前回はプロジェクトに新しいOpenAPIを導入する方法について簡単に説明しました。この記事ではさらに進んで、UIインターフェイスを導入する方法について見ていきます。
主に/scalar/openapidemoという静的ページを追加することで実現されています。ページ内ではscalarのjsが導入されています。scalarについては、https://scalar.com をご覧ください。他の情報は前回の記事とほぼ同じです。コードは以下の通りです:
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi("openapidemo", opt =>
{
opt.UseTransformer((openApiDoc, context, c) =>
{
openApiDoc.Info = new OpenApiInfo
{
Version = "v1.1.1",
Title = "テストAPI",
Description = "これは.NETの標準的なOpenAPIのテストです。"
};
return Task.CompletedTask;
});
opt.UseOperationTransformer((o, c, c1) =>
{
Console.WriteLine("DocumentName:" + opt.DocumentName);
return Task.CompletedTask;
});
});
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/scalar/{documentName}", (string documentName) => Results.Content("""
<!doctype html>
<html>
<head>
<title>Scalar API Reference -- {{documentName}}</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script id="api-reference" data-url="/openapi/{{documentName}}.json"></script>
<script>var configuration = { theme: 'purple',} document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration)</script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>
""", "text/html")).ExcludeFromDescription();
app.MapGet("/order", () =>
{
return new Order()
{
OrderNo = "20210901",
Amount = 100,
OrderDate = DateTime.Now
};
});
app.MapPost("/order", (Order order) =>
{
return new OkResult();
});
app.Run();
/// <summary>
/// 注文
/// <summary>
public class Order
{
/// <summary>
/// 注文番号
/// <summary>
public string OrderNo { get; set; }
/// <summary>
/// 注文金類
/// <summary>
public decimal Amount { get; set; }
/// <summary>
/// 注文日
/// <summary>
public DateTime OrderDate { get; set; }
}
この時、http://localhost:5287/scalar/openapidemo にアクセスすると、視覚的にAPI情報を確認することができます。メイン画面は以下のようになります:
orderのgetリクエスト:
orderのpostリクエスト:
orderのpost方法のTest Request:
Scalarの最大の利点は、多くの異なる言語でAPIを呼び出す方法が組み込まれていることです。これにより、異なる接続者が簡単にコピー&ペーストで利用できるようになり、簡単かつ迅速です。
(Translated by GPT)