0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.NET9でのOpenAPIの顔を持たせる

Posted at

前回はプロジェクトに新しい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リクエスト:

getリクエスト

orderのpostリクエスト:

postリクエスト

orderのpost方法のTest Request:

Test Request

Scalarの最大の利点は、多くの異なる言語でAPIを呼び出す方法が組み込まれていることです。これにより、異なる接続者が簡単にコピー&ペーストで利用できるようになり、簡単かつ迅速です。

(Translated by GPT)

元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247488159&idx=1&sn=a717602db9d5cae8868a99743005e745&chksm=9f004db5a877c4a378f7c4c6acdb5fc2798d799ab6db29dec32436ca9ad28c0b6c76647706ab&token=1053798272&lang=zh_CN#rd&wt.mc_id=MVP_325642

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?