728x90
반응형
Swagger ?
- Open Api Specification(OAS)를 위한 프레임워크 입니다.
- API들이 가지고 있는 스펙(spec)을 명세, 관리할 수 있습니다.
- 처음에 클라이언트와 Interface를 협의할 때 주로 사용합니다.
- 내가 만든 API를 문서화해주고 테스트해볼 수 있는 툴
Swagger의 중요도
처음 프로젝트 시작하는 과정중에 협의 과정을 거쳐야하는데 서버 개발자가 API를
어느정도 완성해가는 과정중 만드는 API정의서 혹은 명세서를 전달해야 한다.
그 형태가 엑셀, PDF, word를 사용해서 전달하게 되면 서버 개발자는 문서화 과정을
거쳐야 해서 피로도가 있고, 프론트 개발자 입장에서도 문서를 보고 데이터가
어떻게 오는지 테스트 해보기 불편하기 때문에 이러한 점을 수월하게
도와주는 툴을 사용하면 좀 더 협업에 있어 수월한 진행에 도움이 된다.
사용 전 세팅 (1)
패키지 설치
- node를 설치 하였다면 npm 명령어를 이용하여 패키지를 설치해줍니다.
npm install swagger-ui-express
npm install swagger-autogen
app.js 수정
- 설치한 라이브러리를 사용하기위해 패키지를 require 해주는 코드를 app.js 혹은 server.js 에 입력해줍니다.
const swaggerUi = require("swagger-ui-express");
// 생성된 json파일을 불러옵니다.
const swaggerFile = require("./swagger-output");
app.use("/swagger", swaggerUi.serve, swaggerUi.setup(swaggerFile));
- 최상단 디렉토리에 swagger.js파일을 생성 후 코드를 입력 해줍니다. (최상단 디렉토리 === app.js와 같은 위치)
const swaggerAutogen = require("swagger-autogen")({ openapi: "3.0.0" });
const options = {
info: {
title: "프로젝트의 타이틀을 입력하는 곳 입니다.",
description:
"프로젝트의 내용을 입력하는 곳 입니다.",
},
servers: [
{
url: "요청을 보낼 url주소를 입력해줍니다. (ex.http://localhost:3000/)",
},
],
// JWT 토큰을 헤더로 보내기 위한 추가 코드입니다.
schemes: ["http"],
securityDefinitions: {
bearerAuth: {
type: "http",
scheme: "bearer",
in: "header",
bearerFormat: "JWT",
},
},
};
// 자동 생성될 json 형식의 파일을 설정합니다.
const outputFile = "./swagger-output.json";
// 자동생성할 routes경로 안에있는 파일을 설정합니다.
const endpointsFiles = [
"./routes/users.js",
"./routes/posts.js"
];
swaggerAutogen(outputFile, endpointsFiles, options);
명령어 실행
- 명령어를 실행하면 설정한 라우터를 기반으로 json형식의 파일이 생성됩니다.
node ./swagger.js
도메인 접속
- 터미널에 npm start 혹은 node app.js 입력 후 설정한 도메인으로 접속합니다.
사용 전 세팅 (2)
"put": {
"tags": ["Posts"],
"security": [
{
"BearerAuth": []
}
],
"summary": "게시글 수정",
"description": "게시글 수정",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"title": {
"type": "string",
"example": "안녕하새요 수정된 게시글 입니다."
},
"content": {
"type": "string",
"example": "안녕하세요 content 입니다."
}
}
}
}
}
},
"parameters": [
{
"name": "postId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "message: 게시글을 수정하였습니다."
},
"400": {
"description": "errorMessage: 로그인된 사용자와 게시자가 다릅니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
},
...
- security - 토큰을 사용하는 곳에 추가합니다.
- tags - 페이지별 기능을 나누어 줄 카테고리 이름를 입력합니다.
- summary - 토글 전 URL 옆에 나올 기능의 이름을 입력합니다.
- description - 기능의 설명을 입력합니다.
- requestBody, application/json - request로 body를 json형식으로 보냅니다.
- schema, type, properties - properties타입을 정하고 body로 보낼 형식의 예제를 입력합니다.
- parameters, name, in, required, shema, type - 파라미터로 받아올 값의 이름, 형식, 필수여부, 타입을 입력합니다.
- responses, description - responses로 보내는 메세지를 입력합니다.
전체코드
더보기
// ./swagger-output.json
{
"openapi": "3.0.0",
"info": {
"title": "hanghea99_week4",
"description": "Node.js Swaager swagger-jsdoc 방식 RestFul API 클라이언트 UI",
"version": "1.0.0"
},
"servers": [
{
"url": "http://3.35.229.128/"
}
],
"paths": {
"/signup": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Users"],
"summary": "회원가입",
"description": "회원 가입",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"nickname": {
"example": "Developer"
},
"password": {
"type": "string",
"example": "1234"
},
"confirm": {
"type": "string",
"example": "1234"
}
}
}
}
}
},
"responses": {
"201": {
"description": "message: 회원 가입에 성공하였습니다."
},
"400": {
"description": "errorMessage: 패스워드가 패스워드 확인란과 동일하지 않습니다."
}
}
}
},
"/login": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Users"],
"summary": "로그인",
"description": "로그인",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"nickname": {
"example": "Developer"
},
"password": {
"type": "string",
"example": "1234"
}
}
}
}
}
},
"responses": {
"200": {
"description": "message: 회원 가입에 성공하였습니다."
},
"400": {
"description": "errorMessage: 회원 가입에 실패하였습니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
}
},
"/posts": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Posts"],
"summary": "게시글 작성",
"description": "",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"title": {
"type": "string",
"example": "안녕하세요 게시글 제목입니다."
},
"content": {
"type": "string",
"example": "안녕하세요 content 입니다."
}
}
}
}
}
},
"responses": {
"200": {
"description": "message: 게시글 작성에 성공하였습니다."
},
"400": {
"description": "errorMessage: 게시글 작성에 실패하였습니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
},
"get": {
"tags": ["Posts"],
"summary": "게시글 목록 조회",
"description": "게시글 목록 조회",
"parameters": [],
"responses": {
"200": {
"description": ""
},
"400": {
"description": "errorMessage: 요청한 데이터 형식이 올바르지 않습니다."
}
}
}
},
"/posts/{postId}": {
"get": {
"tags": ["Posts"],
"summary": "게시글 상세 조회",
"description": "게시글 상세 조회",
"parameters": [
{
"name": "postId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": ""
},
"400": {
"description": "errorMessage: 요청한 데이터 형식이 올바르지 않습니다."
}
}
},
"put": {
"tags": ["Posts"],
"security": [
{
"BearerAuth": []
}
],
"summary": "게시글 수정",
"description": "게시글 수정",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"title": {
"type": "string",
"example": "안녕하새요 수정된 게시글 입니다."
},
"content": {
"type": "string",
"example": "안녕하세요 content 입니다."
}
}
}
}
}
},
"parameters": [
{
"name": "postId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "message: 게시글을 수정하였습니다."
},
"400": {
"description": "errorMessage: 로그인된 사용자와 게시자가 다릅니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
},
"delete": {
"tags": ["Posts"],
"security": [
{
"BearerAuth": []
}
],
"summary": "게시글 삭제",
"description": "게시글 삭제",
"parameters": [
{
"name": "postId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "message: 게시글을 삭제하였습니다."
},
"400": {
"description": "errorMessage: 로그인된 사용자와 게시자가 다릅니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
}
},
"/comments/{postId}": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Comments"],
"summary": "댓글 작성",
"description": "댓글 작성",
"parameters": [
{
"name": "postId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "message: 댓글을 작성하였습니다."
},
"400": {
"description": "errorMessage: 댓글 내용을 입력해주세요."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"comment": {
"example": "안녕하세요 댓글입니다."
}
}
}
}
}
}
},
"get": {
"tags": ["Comments"],
"summary": "댓글 목록 조회",
"description": "댓글 목록 조회",
"parameters": [
{
"name": "commentId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": ""
},
"400": {
"description": "errorMessage: 요청에 실패하였습니다."
}
}
}
},
"/comments/{commentId}": {
"put": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Comments"],
"summary": "댓글 수정",
"description": "댓글 수정",
"parameters": [
{
"name": "commentId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "message: 댓글을 수정하였습니다."
},
"400": {
"description": "errorMessage: 로그인된 사용자와 게시자가 다릅니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"comment": {
"example": "수정된 댓글입니다."
}
}
}
}
}
}
},
"delete": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Comments"],
"summary": "댓글 삭제",
"description": "댓글 삭제",
"parameters": [
{
"name": "commentId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "message: 댓글을 삭제하였습니다."
},
"400": {
"description": "errorMessage: 로그인된 사용자와 게시자와 다릅니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
}
},
"/posts/like": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Likes"],
"summary": "유저 좋아요 목록 조회",
"description": "유저가 좋아요한 게시글 목록을 조회 합니다.",
"responses": {
"200": {
"description": ""
},
"400": {
"description": "errorMessage: 요청에 실패하였습니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
}
},
"/posts/{postId}/like": {
"put": {
"security": [
{
"BearerAuth": []
}
],
"tags": ["Likes"],
"summary": "게시글 좋아요 하기",
"description": "해당 요청을 보내면 게시글을 좋아요 할 수 있습니다.",
"parameters": [
{
"name": "postId",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": ""
},
"400": {
"description": "errorMessage: 요청에 실패하였습니다."
},
"401": {
"description": "errorMessage: 로그인이 필요한 기능입니다."
}
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"in": "header",
"bearerFormat": "JWT"
}
}
}
}
GitHub - JangKroed/hanghea99_week4
Contribute to JangKroed/hanghea99_week4 development by creating an account on GitHub.
github.com
728x90
반응형
'Tools > libraries' 카테고리의 다른 글
Socket.io (0) | 2022.10.14 |
---|---|
Node.js Express Swagger Page 이용하는 방법 (0) | 2022.10.12 |