๐ฏ What is Code-First API Development?
In a nutshell, code-first means you build your API in actual code (JavaScript/TypeScript) and generate an OpenAPI specification from it automatically.
This is way cooler than writing a massive YAML file by hand.
With this approach, you get:
- Self-documenting APIs ๐
- Fewer human errors (because who likes debugging indentation in YAML?)
- Automatic validation and type checking
- An easy-to-maintain API spec
๐ ๏ธ What Weโre Using
Weโre going to use:
- Express.js โ The classic Node.js web framework
- swagger-jsdoc โ Generates OpenAPI specs from JSDoc comments
- swagger-ui-express โ Serves the OpenAPI spec in a fancy UI
๐ Setting Up the Project
First things first, letโs create a new Node.js project:
|
|
Now, install the required dependencies:
|
|
๐๏ธ Creating an Express Server
Letโs start with a basic Express server (server.js
):
|
|
Run it with:
|
|
Boom!
You have a running server.
Not impressed?
Hold my coffee. โ
๐ Defining the OpenAPI Spec with swagger-jsdoc
Now, letโs generate an OpenAPI spec using swagger-jsdoc
.
We add comments above our routes and let the magic happen.
First, create a new file swaggerConfig.js
:
|
|
Now, update server.js
to serve the docs:
|
|
Visit http://localhost:3000/api-docs
and behold the glory of a fully documented API! ๐
โจ Adding Routes with OpenAPI Annotations
Letโs add an actual API endpoint with OpenAPI documentation.
Modify server.js
:
|
|
Now, restart your server and check http://localhost:3000/api-docs
again.
Youโll see your GET /hello
endpoint fully documented.
Neat, huh?
๐๏ธ Adding Parameters and Responses
Letโs level up and add route parameters and response definitions.
Modify server.js
:
|
|
Now, go to http://localhost:3000/api-docs
and test your new personalized greeting API! ๐
๐ฅ Wrapping Up
Hereโs what we did:
- Set up an Express.js server
- Used
swagger-jsdoc
to generate OpenAPI specs - Documented routes directly in JSDoc comments
- Served the docs using
swagger-ui-express
๐๏ธ Key Ideas
Key Idea | Summary |
---|---|
Code-First API Development | Generate OpenAPI specs directly from code |
swagger-jsdoc | Converts JSDoc comments into OpenAPI docs |
swagger-ui-express | Serves the docs in a web UI |
Express.js | Simple Node.js web framework |
OpenAPI | Standard for REST API documentation |