WHY
when we create backend for our app, if we want other people to make request to our backend without knowing the implementation logic, then we need to make a file that lists all the routes and their responses with some description that file is called OpennAPI Specification File
.
- AI Agents can look into this file and do their work accordingly.
- To use any Trading Bot you need this file.
- We could Autogenerate Clients in various Languages (Java , JS, Go...)
Example :
WHAT
The OPENAPI Specification
is a standard way to define your API's in such a way that is understandable by both humans and machines.
1) It is Language-Agnostic [Not particular for any lanuguage]
2) It is typically written in YAML/JSON. [ YAML is more readable as it supports comments but is it indentation sensitive, so mostly it is used in config files whereas JSON is preferred for data exchange.]
3) Developed by swagger and later donated to OPENAPI.
HOW
There are 3 ways to make the spec file
a) Manually [Not Recommended].
b) AutoGenerate It from your code.
1) If you are using languages that has strong types like Rust then it's much easier otherwise we have use some package.
2) In case of NodeJS we could use
With express - https://www.npmjs.com/package/express-openapi (overly detailed)
Without express - https://github.com/lukeautry/tsoa
3) Hono has a native implementation with zod - https://hono.dev/snippets/zod-openapi
c) use any LLM.
Using HONO + ZOD + OPENAPI
STEP-1 : INITIALIZE HONO APP
STEP-2 : Use Zod OpenAPI Hono
Class. Its supports OpenAPI, with this we can validate the values and types using zod and generate OPENAPI Swagger documentation.
Example
STEP-3 : Till now your Spec file generated, if you want swagger page also you can use swaggerUI from @hono/swagger-ui
Example
AutoGenerated Clients
They allow us to communicate with the server with minimum implementation logic using spec file.
To Generate a ts Client use - https://www.npmjs.com/package/openapi-typescript-codegen
1) Store the spec file in openApiSpecFile.json.
2) Generate the Client
npx openapi-typescript-codegen --input ./spec.json --output ./generated
Top comments (0)