Resources
Api design and versioning
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.
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+jsonPros: 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.
// 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); //