Creating Your Own API in Express.js
Express.js is a popular web application framework for Node.js that provides a robust set of features for building APIs. In this article, we will explore how to create your own API using Express.js.
Setup
First, you need to install Node.js and npm if you haven’t already. Once Node.js is installed, you can create a new directory for your project and run the following command to create a new package.json file:
npm init -y
Next, install Express.js using the following command:
npm install express
Creating Your API
Now that Express.js is installed, you can create a new file for your API. For this example, let’s create a simple API that returns a list of users. Create a new file called server.js and add the following code:
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
res.json(users);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Running Your API
To run your API, simply execute the following command in your terminal:
node server.js
Your API is now running on http://localhost:3000/users. You can visit this URL in your web browser or use tools like Postman to make API requests and see the list of users being returned.
Conclusion
Congratulations! You have now created your own API in Express.js. This is just a simple example, but Express.js provides a wide range of features for building more complex APIs. You can explore middleware, routing, and other advanced features to build powerful and secure APIs for your applications.