Master the Basics of Writing GET API for Single Records with Express JS
If you are working with Node.js and Express, it’s important to understand how to create a GET API for retrieving a single record from a database. In this article, we will cover the basics of creating a simple GET API for fetching a single record using Express JS.
Setting Up Express JS
First, you will need to set up a new Express JS project. You can do this by running the following commands in your terminal:
$ mkdir my-express-app
$ cd my-express-app
$ npm init -y
$ npm install express
Once you have set up your project, you can create a new file, for example, `app.js`, and start building your API.
Creating the GET API
Here’s an example of how you can create a simple GET API for retrieving a single record from a database using Express JS:
const express = require('express'); const app = express(); app.get('/api/records/:id', (req, res) => { const id = req.params.id; // Here you would fetch the record with the specified ID from your database // For example, using a database connection or an ORM like Sequelize // Once you have retrieved the record, you can send it back as a JSON response res.json({ id, name: 'Example Record' }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
In the above example, we are creating a GET API endpoint at `/api/records/:id` where `:id` is a placeholder for the record’s ID. When a request is made to this endpoint, Express will extract the `id` parameter from the URL and you can use it to fetch the corresponding record from your database. Once you have the record, you can send it back as a JSON response using the `res.json()` method.
Testing the API
After creating the API, you can test it using a tool like Postman or by making a request to the API from your front-end application. Send a GET request to `http://localhost:3000/api/records/1` (replace `1` with the actual record ID) and you should receive a JSON response with the record data.
Conclusion
In this article, we covered the basics of writing a simple GET API for fetching a single record using Express JS. This is a fundamental skill when building a Node.js and Express application, and understanding how to interact with your database to retrieve data is essential for building a functional API.