How to Create a REST API with Node.js and Express in Under 15 Minutes
This tutorial demonstrates how to quickly build a basic REST API using Node.js and Express.js. We’ll focus on the core concepts, making it easily digestible for beginners. While a fully-fledged API would require more robust error handling and security measures, this example provides a solid foundation.
Prerequisites:
- Node.js and npm (or yarn) installed on your system. Download Node.js
Step 1: Project Setup
- Create a new directory for your project:
mkdir my-rest-api
- Navigate into the directory:
cd my-rest-api
- Initialize a Node.js project:
npm init -y
- Install Express.js:
npm install express
Step 2: Creating the API (app.js)
Create a file named app.js
and paste the following code:
|
|
Explanation:
require('express')
: Imports the Express.js library.app.get('/api/users', ...)
: Defines a GET route for/api/users
. This route will return a JSON array of users.req
represents the request object, andres
represents the response object.res.json(users)
: Sends theusers
array as a JSON response.app.listen(port, ...)
: Starts the server on port 3000.
Step 3: Run the API
Execute the following command in your terminal: node app.js
Step 4: Testing the API
Use a tool like Postman (https://www.postman.com/) or curl to test your API. Make a GET request to http://localhost:3000/api/users
. You should receive a JSON response containing the user data.
Extending the API (Adding POST functionality):
Let’s add a POST route to create a new user. Modify your app.js
file:
|
|
Now you can send a POST request to http://localhost:3000/api/users
with a JSON payload (e.g., {"name": "New User"}
) to add a new user. The response will be the newly created user object. Remember that app.use(express.json())
is essential for parsing JSON from POST requests.
This expanded example provides a more complete foundation for building more complex REST APIs with Node.js and Express.js. Remember to adapt and expand upon this base to fit your specific needs and always prioritize security best practices in a production environment.