[Roast: Day - AI 없이 API 서버 자동 생성
Jul 31, 2024 pm 08:47 PM프런트 엔드 인터페이스를 데이터베이스에 연결하려면 프런트엔드 애플리케이션이 데이터를 검색하고 보낼 수 있도록 API를 설계해야 합니다. 이렇게 하면 계정 생성, 로그인 및 로그아웃 등과 같은 사용자 로직이 활성화됩니다. 로스트와 관련된 모든 로직이 활성화됩니다.
이전에 Express API를 만들어 본 적이 있는데 이번에는 빌드 과정에서 Swagger에 대해 좀 더 배울 수 있는지 알아보고 싶었습니다.
더 스웨거 스위트
Swagger는 Swagger Editor, Swagger CodeGen, Swagger UI의 세 가지 제품을 설계하고 유지 관리하는 회사입니다. 이 세 가지 제품은 함께 작동하여 OpenAPI 호환 애플리케이션(및 설명서)을 더 쉽게 만들 수 있습니다!
계약 사용
Swagger를 사용하여 API를 생성하는 프로세스는 Swagger Editor에서 시작됩니다. 이 도구를 사용하면 계약이라는 것을 만들 수 있습니다. 계약은 이름, 처리할 경로 등 애플리케이션에 대한 다양한 사항을 정의하는 YAML 문서입니다.
YAML 대 JSON
이전에 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은 기계가 읽을 수 있지만 사람도 읽기가 조금 더 쉽기 때문에 이 사양에 적합한 마크업 언어입니다.
API 사양 정의
Swagger Editor를 사용하고 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
경로 정의를 시작하면 CodeEditor의 마법이 살아납니다. 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}라고 합니다. 이는 요청이 이 경로로 전송될 때 서버의 예상되는 동작을 정의한다는 의미입니다. 그 아래에서는 어떻게 되나요?
- get: 이 경로에 대한 GET 요청 엔드포인트를 정의하고 싶다고 Swagger 도구에 알리고, GET 요청에 대한 나머지 정보는 해당 객체 내에 있습니다.
- 태그: 이는 엔드포인트의 선택적 속성이지만 문서에서 엔드포인트를 그룹화할 수 있으므로 UI에서 유용한 속성입니다.
- 요약: 및 설명: Swagger UI의 화면 렌더링에서는 이 두 필드가 서로 다른 위치에 표시됩니다. 요약은 엔드포인트 기능에 대한 간단한 설명을 제공하고, 설명은 추가 세부정보를 제공합니다.
- 매개변수: get:의 이 속성은 경로 매개변수를 지정할 수 있는 곳입니다. 매개변수가 필요한지 여부, 예상되는 데이터 유형 등의 정보를 포함할 수 있습니다.
- 응답: 여기 고기와 감자가 있습니다. 상태 코드 문자열로 식별되는 엔드포인트의 각 유효한 응답은 문서화 및 코드 생성 목적으로 여기에 나열될 수 있습니다.
구성 요소를 건조한 상태로 유지
이와 같은 계약서를 작성하다 보면 같은 내용을 계속해서 입력하게 될 것입니다. 프로그래머라면 우리가 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을 사용하여 애플리케이션을 생성하는 한 애플리케이션과 함께 제공된다는 것입니다.
Let Swagger Code Your API Too!
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.
Is It Really That Easy?
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!
Would You Use It?
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?
Check Out the Project
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









