Code First
The Code-First approach (also known as bottom-up) is a way of designing REST APIs where you start by writing code first—typically the actual backend logic and route handlers—and then (optionally) generate documentation or OpenAPI (Swagger) specs from the existing code.
Pros of Code-First Approach
- Fast development: Great for small teams or when you're iterating rapidly.
- Easy to test early: You can immediately test endpoints using tools like Postman.
- Auto-generate documentation: Use packages like Swagger JSDoc to generate OpenAPI docs from comments.
Example of Code-First Approach
index.js(Main App)
const express = require("express");
const userRoutes = require("./routes/users");
const swaggerUi = require("swagger-ui-express");
const swaggerSpec = require("./docs/swagger");
const app = express();
app.use(express.json());
// API Routes
app.use("/api/users", userRoutes);
// Swagger Docs
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
console.log("Swagger docs at http://localhost:3000/api-docs");
});
routes/users.js(Code-First Route)
const express = require("express");
const router = express.Router();
/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* responses:
* 200:
* description: A list of users
*/
router.get("/", (req, res) => {
res.json([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]);
});
/**
* @swagger
* /api/users:
* post:
* summary: Create a new user
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* responses:
* 201:
* description: User created
*/
router.post("/", (req, res) => {
const { name } = req.body;
res.status(201).json({ id: 3, name });
});
module.exports = router;
docs/swagger.js (Swagger JSDoc Config)
const swaggerJSDoc = require("swagger-jsdoc");
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "Code-First API",
version: "1.0.0",
description: "Simple REST API with Swagger & Code-First Approach",
},
},
apis: ["./routes/*.js"], // Path to the API docs
};
const swaggerSpec = swaggerJSDoc(options);
module.exports = swaggerSpec;