Node.js 환경에서Pythhon의FastapI 같은 OpenAPI 문서의 자동 생성을 구하여Fastify에 손을 대보십시오
13665 단어 Node.jsTypeScriptAPIfastifytech
하고 싶은 일.
Node.만약 js로 API를 쓴다면 OpenAPI 문서를 자동으로 생성하기를 원합니다
배경.
API를 쓸 때 사용하는 Framework에는 파이톤에서 Django와 Flash가 유명하고, 최근 주목받는 Framework에는 FastapI가 있다.FastapI 작업은 노드입니다.js처럼 빠르고 쉽게 파악할 수 있는 특징도 있지만 코드를 쓰면 OpenAPI 문서를 자동으로 제작할 수 있고 웹 인터페이스도 준비할 수 있어 편리하다.
자세한 것을 알고 싶은 사람은 문서를 읽으세요.
같은 일은 노드다.제이스로 하려는 API도 못 할 것 같아서 조사해봤어요.
Fastify만 쓰면 돼요.
Fastify+fastify-swagger 완료.
적당히 만든 견본
해본 일
가져오기
fastify와fastify-swagger 설치
npm i fastify
npm i fastify-swagger
최소한의 실현
먼저 쓰기 시작하다
import * as fastify from 'fastify'
import fastifySwagger from 'fastify-swagger'
const server: fastify.FastifyInstance = fastify.fastify({ logger: true })
server.register(fastifySwagger, {
routePrefix: '/docs',
openapi: {},
exposeRoute: true,
})
server.get('/ping', async (request, reply) => {
return { pong: 'it worked!' }
})
server.listen(3000)
가 시작되고 브라우저에서 http://127.0.0.1:3000/docs에 액세스할 때 이동합니다.조회 매개 변수를 전달해 보다
query와response를 정의하는 schema를 지정합니다.
나는 TS의 유형 정의에 푹 빠졌다.일단 움직여.나는 정확한 작법을 알고 싶다.
// queryとresponseのschemaを定義する
const schema1: fastify.RouteShorthandOptions = {
schema: {
querystring: {
type: 'object',
properties: {
test_query: {
type: 'number',
},
},
},
response: {
200: {
type: 'object',
properties: {
test_response: {
type: 'number'
},
},
},
},
},
}
// デフォルトだとqueryのTSとしての型定義がunknownなので、定義してあげる
interface Request1 extends fastify.RequestGenericInterface {
Querystring: {
test_query: number
}
}
server.get<Request1, unknown, fastify.FastifySchema>('/querytest', schema1, async (request, reply) => {
return { test_response: request.query.test_query }
})
이동경로 매개 변수 전달 시도
질의 매개변수와 거의 동일
// paramsとresponseのschemaを定義する
const schema2: fastify.RouteShorthandOptions = {
schema: {
params: {
type: 'object',
properties: {
test_param: {
type: 'string',
},
},
},
response: {
200: {
type: 'object',
properties: {
test_response2: {
type: 'string'
},
},
},
},
},
}
// デフォルトだとParamsのTSとしての型定義がunknownなので、定義してあげる
interface Request2 extends fastify.RequestGenericInterface {
Params: {
test_param: string
}
}
server.get<Request2, unknown, fastify.FastifySchema>('/paramstest/:test_param', schema2, async (request, reply) => {
return { test_response2: request.params.test_param }
})
이동감상
Reference
이 문제에 관하여(Node.js 환경에서Pythhon의FastapI 같은 OpenAPI 문서의 자동 생성을 구하여Fastify에 손을 대보십시오), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/ibaraki/articles/7a6368bdfb890f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)