
ASP.NET Web API快速入門介紹
cd ./todo-app
git init
git add .; git commit -m "Initial commit";
npm i express-openapi -s
// ./app.js
...
app.listen(3030);
...
// OpenAPI routes
initialize({
app,
apiDoc: require("./api/api-doc"),
paths: "./api/paths",
});
module.exports = app;
請注意,模型中定義了?Todo?的類型,將在路由處理程序中引用。
// ./api/api-doc.js
const apiDoc = {
swagger: "2.0",
basePath: "/",
info: {
title: "Todo app API.",
version: "1.0.0",
},
definitions: {
Todo: {
type: "object",
properties: {
id: {
type: "number",
},
message: {
type: "string",
},
},
required: ["id", "message"],
},
},
paths: {},
};
module.exports = apiDoc;
每個處理程序都聲明它支持哪些操作(GET、POST …),對每個操作的回調,以及該處理程序的?apiDoc?OpenAPI 模型。
// ./api/paths/todos/index.js
module.exports = function () {
let operations = {
GET,
POST,
PUT,
DELETE,
};
function GET(req, res, next) {
res.status(200).json([
{ id: 0, message: "First todo" },
{ id: 1, message: "Second todo" },
]);
}
function POST(req, res, next) {
console.log(About to create todo: ${JSON.stringify(req.body)}
);
res.status(201).send();
}
function PUT(req, res, next) {
console.log(About to update todo id: ${req.query.id}
);
res.status(200).send();
}
function DELETE(req, res, next) {
console.log(About to delete todo id: ${req.query.id}
);
res.status(200).send();
}
GET.apiDoc = {
summary: "Fetch todos.",
operationId: "getTodos",
responses: {
200: {
description: "List of todos.",
schema: {
type: "array",
items: {
$ref: "#/definitions/Todo",
},
},
},
},
};
POST.apiDoc = {
summary: "Create todo.",
operationId: "createTodo",
consumes: ["application/json"],
parameters: [
{
in: "body",
name: "todo",
schema: {
$ref: "#/definitions/Todo",
},
},
],
responses: {
201: {
description: "Created",
},
},
};
PUT.apiDoc = {
summary: "Update todo.",
operationId: "updateTodo",
parameters: [
{
in: "query",
name: "id",
required: true,
type: "string",
},
{
in: "body",
name: "todo",
schema: {
$ref: "#/definitions/Todo",
},
},
],
responses: {
200: {
description: "Updated ok",
},
},
};
DELETE.apiDoc = {
summary: "Delete todo.",
operationId: "deleteTodo",
consumes: ["application/json"],
parameters: [
{
in: "query",
name: "id",
required: true,
type: "string",
},
],
responses: {
200: {
description: "Delete",
},
},
};
return operations;
};
npm i swagger-ui-express -s
// ./app.js
...
// OpenAPI UI
app.use(
"/api-documentation",
swaggerUi.serve,
swaggerUi.setup(null, {
swaggerOptions: {
url: "http://localhost:3030/api-docs",
},
})
);
module.exports = app;
這就是我們最終獲得的效果:
這個 SwaggerUi 是自動生成的,你可以在 http://localhost:3030/api-documentation 訪問它。
?? 恭喜!
當你進行到文章的這里時,你應該創建好了一個完全可運行的 Express 應用程序,其與 OpenAPI 完全集成。
現在,通過使用在 http://localhost:3030/api-docs 中定義的模型,我們可以輕松生成測試、模擬服務器、類型,甚至客戶端!
我們只是淺淺涉獵了 OpenAPI 所能做到的事情。但是我希望這篇文章能夠讓你了解標準 API 定義模式是如何在可見性、測試、文檔和整體置信度方面幫助構建 REST API 的。
謝謝你看到最后,happy coding!
原文鏈接:https://www.freecodecamp.org/news/how-to-build-explicit-apis-with-openapi/
本文章轉載微信公眾號@若川視野