-
OpenAPI와 스웨거를 활용한 실전 API 설계를 읽고 ... (2)개발하면서/타인글보면서 2024. 5. 8. 20:20반응형
지난 글에 선 만들어져 있는 API를 OpenAPI로 표현하는 법을 배웠다면
이번에는 하나의 서비스를 백지상태부터 오픈기까지의 과정 소개한다.
책에서는 아이디어 구상과 팀 구성, 도메인 모델 설계와 프로젝트 구현에 필요한 계획 수립 과정 등을 소개하는데
그중 기술적인 부분만 일부 정리했다.
실무에 적용하면서 겪을만한 내용들이 있으니 관심이 있다면 꼭!! 책을 읽어보길 추천한다.
관심이 없더라도 이 책을 읽어보는 걸 추천한다. 응??
공통 스키마 참조
리뷰에서 평점을 나타내는 rating 프로퍼티의 범위가 최고 5점에서 최고 10점으로 변경된다고 했을 때
정의한 rating 프로퍼티를 모두 찾아 maximum: 5를 10으로 바꿔야 한다. 사람이 직접!!오류 가능성이 커지므로 한 번만 정의하고 재사용할 수 있도록 공통 스키마를 만드는 법을 소개한다.
User 스키마 정의
components -> schemas -> [Schema name]으로 스키마를 정의한다.
openapi: 3.0.3 info: title: PetSitter API version: "0.1" paths: {} components: schemas: Users: type: object properties: id: type: integer email: type: string password: type: string full_name: type: string roles: type: array items: type: string
CRUD 응답 코드
연산 상태 코드 응답 본문 생성 201 비어있고 Location 헤더 반환 읽기 200 리소스 또는 컬렉션을 포함하는 객체 수정 200 리소스 삭제 204 비어 있음 schema 밑에 type: object가 오지 않고 $ref를 이용한다.
$ref: '#/components/schemas/Users' 로 component에 정의한 Users 스키마를 참조한다.
openapi: 3.0.3 info: title: PetSitter API version: "0.1" paths: /users: post: summary: Register User requestBody: content: application/json: schema: $ref: '#/components/schemas/Users' responses: '201': description: Created headers: Location: schema: type: string /users/{userId}: parameters: - schema: type: integer name: userId in: path required: true delete: summary: Delete User responses: '204': description: No content components: schemas: Users: #...
OpenAPI 목서버 만들어 프론트엔드 구현
Prism library로 목서버를 만들고 이를 연동하여 프런트엔드 개발 방법을 배운다.
그리고 누락된 API를 발견하고 개선하는 과정을 소개한다.Prism-cli를 이용해서 목서버를 띄운다. https://docs.stoplight.io/docs/prism/674b27b261c3c-prism-overview
$> prism mock -p 8080 ./openapi.yaml
API 호출도 잘 되고 페이지 표시도 되지만 의미 있는 테스트라고 보기엔 어렵다.
이때 Swagger UI의 try-it-out 기능과 비슷하게, 예제를 추가해서 다양한 목 데이터를 응답값으로 보낼 수 있다.
예제가 여러 개 있을 때 Prefer Header를 이용하여 테스트도 가능하다.
테스트 완료 후 운영에 반영할 때는 Prefer 헤더만 제거해 주면 된다.
$> curl -H "Prefer: example=two-items" http://localhost:8080/users/1/job-applications $> curl -H "Prefer: code=404" http://localhost:8080/users/1/job-applications $> # https://docs.stoplight.io/docs/prism/beeaad4dc0227-prism-cli#modifying-responses
보안 정의
총 14개의 연산(API) 중 12개는 인가를 적용해야 하고, 2개(User Regist, Start Session)는 인가가 필요 없다면
12개에 security를 적용하는 것보다글로벌 보안을 한번 정의하고 2개 연산에 예외를 적용하는 것이 관리가 용이하다.
openapi: 3.0.3 #... security: - SessionToken: [] # <-- global security paths: /users: post: security: [] # <-- exclude security /sessions: post: security: [] # <-- exclude security components: schemas: securitySchemes: SessionToken: type: apiKey in: header name: Authorization
반응형