Quick Answer: Use Express.js to create a lightweight, scalable REST API in Node.js.
You can build a functional REST API by installing the Express framework, defining routes for HTTP methods like GET and POST, and connecting them to your data logic. The process typically takes less than an hour for a basic setup, allowing you to serve JSON data to clients efficiently.
What Do You Need Before Starting?
Before writing code, ensure your environment is ready. You need Node.js installed on your machine, which provides the runtime environment. You also need a text editor, such as Visual Studio Code or Sublime Text, to write your JavaScript files.
- Node.js version 14 or higher
- A package manager (npm or yarn)
- A code editor
- Basic knowledge of JavaScript syntax
Verify your installation by opening your terminal and typing node -v. If a version number appears, you are ready to proceed. If not, download the latest stable release from the official Node.js website.
How Do You Set Up the Project Structure?
Create a new directory for your project. Inside this folder, initialize a new npm package. This step generates a package.json file that tracks your dependencies and scripts.
- Open your terminal and navigate to your desired location.
- Run
mkdir my-apito create the folder. - Enter the folder using
cd my-api. - Initialize the project with
npm init -y. - Install Express using
npm install express.
Once installed, create a file named index.js. This will be the entry point for your application. Keep your project structure simple at first; you can add folders for controllers or models later as complexity grows.
How Do You Create Your First Route?
Routes define how your application responds to specific HTTP requests. In Express, you use the app.get(), app.post(), app.put(), and app.delete() methods to handle these requests. Each route consists of a URL path and a handler function.
Write the following code in your index.js file:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`API running on http://localhost:${port}`);
});
This snippet imports Express, creates an instance of the application, and defines a root route. When a client visits the root URL, the server sends back "Hello World". Save the file and run it with node index.js. Visit http://localhost:3000 in your browser to see the result.
How Do You Handle Data with JSON?
REST APIs primarily exchange data in JSON format. To send JSON responses, use the res.json() method instead of res.send(). This automatically sets the correct content-type header.
For receiving data, you must parse the request body. Install the built-in middleware or use express.json() if you are on a recent version of Express. Add this line after creating your app instance:
app.use(express.json());
Now, when a client sends a POST request with a JSON body, you can access it via req.body. For example, to echo back received data:
app.post('/data', (req, res) => {
const newData = req.body;
res.json({ message: 'Data received', data: newData });
});
Test this endpoint using a tool like Postman or curl. Send a JSON object in the request body and observe the response. This confirms your API can both read and write structured data.
Where Do People Go Wrong with Error Handling?
A common mistake is ignoring errors. If a database call fails or input is invalid, your server might crash or return unhelpful messages. Always wrap asynchronous operations in try-catch blocks or use Express's error-handling middleware.
Define a central error handler at the end of your route definitions:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Ensure you validate incoming data before processing it. Libraries like Joi or Validator can help check types and formats. Returning clear status codes, such as 400 for bad requests or 404 for missing resources, helps clients understand what went wrong without guessing.
How Do You Connect to a Database?
To make your API useful, it needs persistent storage. You can connect to databases like MongoDB, PostgreSQL, or MySQL using appropriate drivers or Object-Relational Mappers (ORMs).
For MongoDB, install Mongoose with npm install mongoose. Then, establish a connection in your main file:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });
Create schemas and models to define your data structure. These models allow you to perform CRUD (Create, Read, Update, Delete) operations easily. Replace your static JSON responses with calls to these model methods. For example, use Model.find() to retrieve all documents and send them as a JSON array.
What Are the Next Steps for Production?
Your local API works, but deploying it requires additional considerations. Never expose development servers directly to the internet. Use a process manager like PM2 to keep your application running and restart it if it crashes.
Add security measures such as Helmet to set secure HTTP headers and CORS to control which domains can access your API. Implement rate limiting to prevent abuse. Finally, choose a hosting provider that supports Node.js applications, ensuring your environment variables for database credentials are stored securely and never committed to version control.