Node Rest API Tutorial
On the command line, create a new folder, navigate to it, and then run
npm will ask a number of questions which you can hit Return to leave as the default for now.
Once complete, npm will create a
package.json file that tracks project information and dependencies. To confirm you have this file, type
Next install Express by running this command:
Your First REST API
We can create a REST API with one file and six lines of code. Ready? Create a new file named
index.js with the following code:
What we’ve done here is:
- imported the Express module
- initialized the Express object
- created a handler for
GET /apiwhich responds to requests with a JSON object
- told Express to listen to HTTP requests on port 3000
- added a
console.logstatement to confirm the server is running
Now run this on the command line:
If you open your web browser to localhost:3000/api you’ll see our single REST API endpoint running.
Add Multiple Routes
api/todos endpoint let’s add multiple routes corresponding to multiple todos.
The new code looks as follows:
On the command line, press CTRL + the “C” key to stop the server. Then type
node index.js again to restart the server. If you again navigate to localhost:3000/api you’ll see multiple routes now.
Multiple Endpoints and Routes
For our final step, let’s add an additional endpoint for users at
/api/users and populate it with routes.
If we navigate to
localhost:3000/api/todos we’ll see it’s the same but we can also go to
localhost:3000/api/users and see our new “users” endpoint.