.Net Core Web Api_筆記21_Swagger及OpenAPI介紹與配置使用方式_API管理與測試探討

 

Swagger 是一套web api管理於測試的工具
甚至可協助提供自訂API規格文件與呼叫回應方式的描述


以下是台中交通API的實際案例



於2015年Swagger就捐贈給OpenAPI計畫
也因此有OpenAPI的別稱

不過通常習慣將OpenAPI視為一種規範而Swagger則是實踐該規範的工具。
OpenAPI  注重開發者寫出來的API可跟調用呼叫者很直接的合作而不用透過程式碼存取


我們可從OpenAPI規範看出訪問的URL與HTTP Method採用何種(GET,PUT,POST...)
跟參數與資料型別

因此用戶端可以很清楚如何去呼叫使用更能讓二次開發者能夠無縫接軌

Swagger其實相當於一個根據OpenAPI規範發展出來一系列產品的品牌。
旗下也有諸多不同的工具比方OpenAPIGenerator , NSwag , Swashbuckle ....

Swagger UI 則是提供了Web 介面 使用OpenAPI規範提供資訊。

而我們於.NET Core開發框架則可透過middleware方式註冊NSwag , Swashbuckle

Swagger 3 Web UI



Swagger 2 Web UI





.net core web api應用Swagger配置使用

在此我拿之前跑的這幾篇最終產出的專案去配置



到Nuget套件去下載安裝NSwag.AspNetCore







緊接著我們到Starup的ConfigureServices方法去註冊服務

再到Configure去啟用OpenAPI跟SwaggerUI的中間件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerDocument();//註冊NSwag提供的服務
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }            

            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthorization();

            app.UseOpenApi();//啟用OpenAPI,預設路由/swagger/v1/swagger.json

            app.UseSwaggerUi3();//啟用SwaggerUi version 3

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}



最後就是見證奇蹟的時刻(對於懶得寫API文件的開發者來說真的是一大福音)
要查看Swagger API 自動幫我們掃描所有API 方法後產生出來的WEB API Document
預設路由/swagger
會自動跳轉至/swagger/index.html






而且還真的能執行存取異動














Ref:

OpenAPI Specification

使用 Swagger/OpenAPI ASP.NET Core web API 檔


NSwag 與 ASP.NET Core 使用者入門

Swashbuckle 與 ASP.NET Core 使用者入門














留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients