iT邦幫忙

0

Day 14|Swagger UI 與 OpenAPI:用網頁測試你的 API

c#
  • 分享至 

  • xImage
  •  

今天的學習目標

  • 理解 Swagger UI 與 OpenAPI 的用途
  • 在 TaskFlow2.Api 安裝 Swagger UI
  • 設定 Program.cs
  • 使用網頁介面測試 GET、POST、PUT、DELETE
  • 理解常見 HTTP 回應狀態碼

什麼是 Swagger UI

OpenAPI 負責描述 API,Swagger UI 負責顯示與測試 API
Swagger UI 會列出 TaskFlow 的 API,例如:

  • GET /api/tasks
  • GET /api/tasks/{id}
  • POST /api/tasks
  • PUT /api/tasks/{id}
  • DELETE /api/tasks/{id}
    按下 Try it out 後就可以輸入參數、發送請求、查看結果

安裝 Swagger UI 套件

們使用微軟文件介紹的整合方式。[]https://learn.microsoft.com/fil-ph/aspnet/core/fundamentals/openapi/using-openapi-documents?view=aspnetcore-10.0&utm_source=chatgpt.com(http://)

dotnet add package Swashbuckle.AspNetCore.SwaggerUI

這個套件會讓我們在瀏覽器中使用 Swagger UI,而不需要自行設計測試網頁。

修改 Program.cs

var builder = WebApplication.CreateBuilder(args);

// OpenAPI
builder.Services.AddOpenApi();

// Controller
builder.Services.AddControllers();

var app = builder.Build();

// 開發環境才啟用 OpenAPI 和 Swagger UI
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();

    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/openapi/v1.json", "v1");
    });
}

app.UseHttpsRedirection();

// 啟用 Controller 路由
app.MapControllers();

// 測試路由
app.MapGet("/test", () => "伺服器正常運作!");

app.Run();

結果
https://ithelp.ithome.com.tw/upload/images/20261020/20184430LZFAQz1efu.png

使用 Swagger UI 測試 CRUD

選擇 API,例如 GET /api/tasks
按下 Try it out
輸入必要的參數或 JSON
按下 Execute
查看 Server response


*提醒邦友,使用第三方服務/API 時,請務必評估資安風險與隱私保護
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言