Resources

Api design and versioning

Effective API Design and Versioning are the blueprints that ensure a backend system is predictable, scalable, and maintainable over time. Without a clear design strategy, APIs become difficult for frontend developers to consume and risky to update.

1. RESTful API Design Principles


Theory: Representational State Transfer (REST) is an architectural style that uses standard HTTP methods to perform operations on resources.

  • Nouns, Not Verbs: Use resource-based URLs (e.g., /users) rather than action-based ones (e.g., /getUsers).

  • HTTP Methods: Use the correct method for the intent:

    • GET: Retrieve data.

    • POST: Create a new resource.

    • PUT: Update an existing resource (replace).

    • PATCH: Partial update.

    • DELETE: Remove a resource.

  • Statelessness: Each request from a client must contain all the information necessary to understand and complete the request. The server should not store "context" about the client's session state.


2. API Versioning Strategies

Theory: Versioning allows you to introduce "breaking changes" (like renaming a field or changing a data structure) without breaking existing client applications that rely on the old version.

A. URI Versioning (Most Common)

Theory: The version number is included directly in the URL path.

  • Example: [https://api.example.com/v1/users](https://api.example.com/v1/users)

  • Pros: Highly visible and easy to test in a browser.

  • Cons: Can lead to "URL bloat" as versions accumulate.

B. Header Versioning (Media Type)

Theory: The version is passed in a custom request header or the Accept header.

  • Example: Accept: application/vnd.example.v1+json

  • Pros: Keeps URLs clean and reflects the "content negotiation" philosophy of HTTP.

  • Cons: Harder to test and less discoverable for developers.

C. Query Parameter Versioning

Theory: The version is passed as a parameter at the end of the URL.

  • Example: [https://api.example.com/users?version=1](https://api.example.com/users?version=1)


3. Implementation in Express


Theory: In Express, you can implement URI versioning using Router modules to keep your code organized.

JavaScript

// routes/v1/index.js
const v1Router = express.Router();
v1Router.use('/users', require('./userRoutes'));
app.use('/api/v1', v1Router); //

// routes/v2/index.js
const v2Router = express.Router();
v2Router.use('/users', require('./userRoutesV2'));
app.use('/api/v2', v2Router); //

.