為了將我的前端介面連接到資料庫,我需要設計一個 API 來允許前端應用程式檢索和發送資料。這將啟用我的用戶邏輯,例如建立帳戶、登入和登出等。它將啟用圍繞烘焙的所有邏輯。
我之前曾建立過 Express API,但這次我想看看是否可以在建置過程中了解更多有關 Swagger 的知識。
Swagger 是一家設計和維護三種產品的公司,Swagger Editor、Swagger CodeGen 和 Swagger UI。這三個產品攜手合作,讓創建符合 OpenAPI 的應用程式(和文件)變得更加容易!
使用 Swagger 建立 API 的過程從 Swagger 編輯器開始。該工具允許您創建所謂的合約。合約是一個 YAML 文檔,它定義了有關應用程式的不同內容,例如名稱、它將處理的路由等等。
如果您以前沒有使用過 YAML,它是一種更寬鬆的基於物件的標記語言,與 JSON 有一些相似之處,但更容易快速輸入。以下是 JSON 和 YAML 中相同內容的範例:
// JSON Example { "name": "ThisApp", "description": "An example of data.", "list": [ "option1", "option2", "option3" ], "object": { "key": "value" } }
# YAML Example name: ThisApp description: An example of data. list: - option1 - option2 - option3 object: key: value
請注意,YAML 雖然仍然是機器可讀的,但對於人類來說也更容易閱讀,這使其成為此規範的絕佳標記語言。
使用 Swagger 編輯器並遵循 OAS,您可以編寫通常編程到 API 中的所有內容。
在頂層,您將定義應用程式的細節:
openapi: 3.0.3 info: title: Roast - Know Your Home Roasts description: # This will appear in the API UI version: 1.0.0 servers: - url: # A url to one or more servers here tags: These are groups of paths - name: user description: Operations for your user - name: roast description: Access to roasts paths: # Define all of your paths in this object components: # Define reusable pieces of code here
當您開始定義路徑時,程式碼編輯器的魔力就會顯現出來。採用我定義的以下路徑,透過 id 取得單一烘焙。
# ... contract information paths: # ... users paths, etc. /roasts/{roastId}: get: tags: - roast summary: Get roast by id description: Must include a valid roast id parameters: - $ref: '#/components/parameters/roastIdParam' responses: '200': description: Successful operation content: application/json: schema: $ref: "#/components/schemas/Roast" '400': $ref: '#/components/responses/Invalid' '404': $ref: '#/components/responses/NotFound'
讓我們分解這個物件。首先,它被稱為/roasts/{roastId}。這意味著我們正在定義當請求發送到此路由時伺服器的預期行為。下面會發生什麼事?
開發這樣的合約,您可能會發現自己一遍又一遍地輸入相同的內容。作為一名程式設計師,您可能知道我們要遵循 DRY 原則:「不要重複自己」。例如,當定義一個必要的請求體時,可能會有多個端點需要同一個物件。
這就是組件的用武之地。對於這個範例,您可以定義一個架構,然後使用 $ref 在合約中的任何位置引用該架構: .
所以,在我的合約底部,我有一個組件:物件。
components: schemas: Roast: # An arbitrary name to identify the schema type: object properties: id: type: integer format: int64 example: 10 ## Include all other properties
這個組件物件包含一個名為 Roast 的模式,所以現在,如果我需要指定需要在請求中發送該對象,例如在對 /roast 的 POST 請求中發送以添加新的烘焙。我可以這樣引用該物件:
/roast: post: # additional specifications requestBody: content: application/json: schema: $ref: '#/components/schemas/Roast'
您也可以在定義參數和規範的許多其他重複部分中執行此操作!
當您在 Swagger 編輯器中打字時,右側視窗中的 Swagger UI 一直在不斷更新。 Swagger UI 正在更新將成為您的 API 文件的內容!這意味著您不必稍後返回並自己編寫文件。
最好的部分是,它將與您的應用程式一起提供(只要您使用 CodeGen 建立它)。
Once you feel like your API is up to spec, you can have a working server in 17 different languages/frameworks in seconds! Just click Generate Server, and select your flavor and CodeGen reads your OAS spec and downloads a server.
In Node, your code comes out in a few different directories.
generated-server/ |-- api/ |-- controllers/ |-- service/ |-- utils/ |-- README.md |-- index.js |-- package.json
The api directory contains your OpenAPI spec. The controllers directory contains a file for each of your path groups, with exported functions specifically for handling the unique paths and operations of your application. The service directory, is where you will hook these operations up to your database and perform the business logic of the application, and utils contains functions that help read and write data.
Your server will actually live in index.js.
Yes! Well, sort of.
CodeGen does in fact make a working server for you, but it's still up to you to hook up the database and design the logic of the application! But, it gives you a complete and organized skeleton that you can work in!
Here's an example of the code that it output for my POST request to /roasts .
// controllers/Roast.js // ... module.exports.addRoast = function addRoast (req, res, next, body) { Roast.addRoast(body) .then(function (response) { utils.writeJson(res, response); }) .catch(function (response) { utils.writeJson(res, response); }); }; // service/RoastService.js // ... exports.addRoast = function(body) { return new Promise(function(resolve, reject) { var examples = {}; examples['application/json'] = { "notes" : "Doesn't taste as good as last time... I wonder if the weather is making the beans roast faster now that it's warmer", "heatLevel" : "Med", "origin" : "Ethiopian", // ... "id" : 10, }; if (Object.keys(examples).length > 0) { resolve(examples[Object.keys(examples)[0]]); } else { resolve(); } }); }
The above code was entirely generated by Swagger CodeGen. However, it won't actually add a roast object anywhere. This is creating a mock object and sending it back. But, after hooking up a Postgres database, and creating queries with this logic inside the service, the API will be fully operational!
I loved working with Swagger on this API, it was the first time that I committed to learning some of the intricacies of OAS to generate the server. The only rub that I have with it is that the docs are not formatted the best, and they can be hard to navigate searching for what you want to add to the server.
But, once you're familiar with OAS, this tool can save a ton of time. Not only do you have extremely thorough documentation when you're done, but you can treat the generated code as a to-do list of the functions and logic that you need to implement as you build!
Would you give it a try?
If you want to keep up with the changes, fork and run locally, or even suggest code changes, here’s a link to the GitHub repo!
https://github.com/nmiller15/roast
The frontend application is currently deployed on Netlify! If you want to mess around with some features and see it in action, view it on a mobile device below.
https://knowyourhomeroast.netlify.app
Note: This deployment has no backend api, so accounts and roasts are not actually saved anywhere between sessions.
以上是[Roast:Day - 無需 AI 自動建立 API 伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!