For a simple API, being able to create separate versions may not be necessary. However, for larger API’s with more complex requirements, it may be necessary to make breaking changes that you don’t want to expose your users to. In this case, your best bet is to create a new version of the API so that both the initial version and the new version can be run in parallel while you transition your users to an updated client that plays nicely with the new version of your API.
In a command/terminal window, navigate to a new folder to create the project in. In that folder run
Follow the prompts to configure the new nodejs project.
Open the project in your code editor of choice.
Create an app.js file and install express via a terminal -
npm i express
We’ll now set up the simplest express server possible:
Then, in the project directory create a Routes folder. This folder will hold the separate directories that control the navigation routes to our API endpoints.
Now, in this Routes folder there are a few options on how we proceed:
- We can put individual version route files directly into this folder:
- Or, we can create version subfolders:
- Or, for more complex API’s, we might want to create version subfolders along with folders for groupings of similar logic functions:
Now, in the app.js file we’ll add the routing options:
With this configuration, when we run the server locally, we can navigate to http://localhost:3000/api/v1/users to run the version 1 variant.
We can also navigate to http://localhost:3000/api/v2/users to run the version 2 variant.