A CRUD API
in web development, refers to an API that supports the four basic operations: Create, Read, Update, and Delete. These operations correspond to the standard HTTP methods:
- GET: Used for retrieving data from the server.
- POST: Used for creating new data on the server.
- PUT: Used for updating existing data on the server.
- DELETE: Used for removing data from the server.
Virtually every web application interacts with a database to perform these operations. Whether it’s a social media platform, an e-commerce website, or a weather app, they all rely on CRUD operations to manage data.
For example, consider a messaging application like WhatsApp adding an edit feature. This feature involves updating existing messages, demonstrating the “U” (Update) operation in CRUD.
When building a web API, CRUD operations are fundamental. Your API provides endpoints that allow client applications (such as web or mobile apps) to perform these operations on the server.
Node.js is
an open-source, cross-platform runtime environment for executing JavaScript code outside of a web browser. It is commonly used to build back-end services, also known as APIs. Here’s why Node.js is a popular choice for backend development:
- JavaScript Everywhere: With Node.js, you can use JavaScript for both frontend and backend development, facilitating easier transitions for developers.
- Scalability: Node.js enables easy scaling of applications, making it suitable for large-scale projects.
- Performance: Node.js is fast and non-blocking due to its asynchronous event-driven architecture.
- Vibrant Ecosystem: Node.js has a thriving community and a vast array of packages and libraries available.
To install Node.js, follow these steps:
- Download the Mac/Windows installer from the Node.js website.
- Choose the Long-Term Support (LTS) version.
- Run the installer and follow the prompts. Accept the default installation settings.
- To verify the installation, open your terminal and run the command
node -v
. (For Windows, you may need to restart your command prompt before running the command.)
node –version
Express is a fast, unopinionated, and minimalist web backend or server-side web framework for Node.js. It provides a robust set of features for building web applications and APIs with Node.js, allowing developers to create flexible and efficient server-side solutions.
Here’s why you might choose Express:
Simplicity and Flexibility: Express simplifies the process of building web applications and APIs with Node.js by providing a straightforward and flexible framework. It allows developers to structure their applications according to their specific requirements.
Performance: Express is lightweight and fast, making it well-suited for handling high-traffic applications and APIs. It efficiently handles HTTP requests and responses, optimizing performance.
Middleware: Express features a powerful middleware mechanism that enables developers to add functionality to their applications at various points in the request-response cycle. Middleware can handle tasks such as parsing request bodies, authenticating users, and logging requests.
Community and Ecosystem: Express has a large and active community, with a wide range of plugins and middleware available to extend its functionality. This rich ecosystem makes it easy to integrate Express with other tools and services.
In summary, Express is an essential tool for Node.js developers, providing the foundation for building scalable, high-performance web applications and APIs.
To set up your development environment and create a basic server on your local computer, follow these steps:
Step #1 – Create a Directory: Create a directory or folder on your computer where you want to store your project files. You can do this using your computer’s file explorer or using the command line. For example, you can use the following command in your terminal to create a directory named “my-server”:
mkdir my-server
Step #2 – Navigate to the Directory: Navigate into the newly created directory using the command line. For example:
cd my-server
Step #3 – Create an index.js File: Create an index.js file inside the folder. You can do this using a text editor or through the command line. For example, you can use the following command to create an index.js file:
touch index.js
This command creates an empty index.js file in the current directory.
Alternatively, if you’re using a code editor like Visual Studio Code, you can open the folder in the editor and create a new file named index.js.
Once you’ve completed these steps, you’re ready to start building your basic server with Node.js and Express in the index.js file.
Step #4 – Initialize NPM inside the folder by running this command in your terminal:
npm init -y
The command will create a package.json file with default values.
Step #5 – Install Express
With the package.json file created, you can now install Express.js. Run the following command in your terminal:
npm install express
Open and check package.json file
{
"name": "my-node-project",
"version": "1.0.0",
"description": "A sample Node.js project",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node",
"sample",
"project"
],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"express": "^4.17.1",
"lodash": "^4.17.21"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
This package.json
file includes:
name
: Name of the project.version
: Version number of the project.description
: Brief description of the project.main
: Entry point file of the project.scripts
: Custom scripts that can be run with npm.keywords
: Keywords related to the project.author
: Author of the project.license
: License under which the project is distributed.dependencies
: List of packages required by the project for production.devDependencies
: List of packages required for development, such as testing and build tools.
How to Set up a server for Your CRUD Restful API with Node.js and Express
Step 1 – Write your Server Application Code inside the index.js file
import express from 'express';
import bodyParser from ‘body-parser
const app = express();
const PORT = 5000
app.use(bodyParser.json());
app.listen(PORT, () => console.log(`Server running on port: http://localhost:${PORT}`));
Imports:
- The code imports the
express
module to create an Express application. - It also imports the
body-parser
middleware to parse incoming request bodies.
- The code imports the
Express App Initialization:
- An instance of the Express application is created and stored in the variable
app
.
- An instance of the Express application is created and stored in the variable
Constants:
- The
PORT
constant is defined with the value5000
, specifying the port number on which the server will listen for incoming requests.
- The
Middleware:
- The
app.use()
function is used to mount middleware functions in the Express application pipeline. - Here,
body-parser
middleware is used with thejson()
method to parse JSON request bodies. - This middleware parses incoming request bodies and makes them available under the
req.body
property of the request object.
- The
Server Listening:
- The
app.listen()
method is called to start the Express server. - It takes the
PORT
constant as the first argument and a callback function as the second argument. - The callback function logs a message indicating that the server is running and listening for requests.
- The
Overall, this code sets up an Express server with JSON body parsing middleware, listening on port 5000. When a request is received, the server will parse the JSON body and make it available for further processing in route handlers.
Step 3- Start your server
To start your server, navigate to the directory where your server file (index.js
in this case) is located using your terminal or command prompt. Then, run the following command:
node index.js
Now your server should be running on port 5000.
Step 4- Install Nodemon
To install Nodemon, you can use npm, the Node.js package manager. Nodemon is a tool that helps in development by automatically restarting the Node.js application when file changes are detected. Here’s how you can install Nodemon:
npm install -g nodemon
This command installs Nodemon globally on your system, allowing you to use it from any directory in your terminal.
After installing Nodemon, you can use it to start your server instead of the node
command. For example:
nodemon index.js
With Nodemon, your server will automatically restart whenever changes are made to the server files, making the development process smoother and more efficient.
Navigating the realm of API requests is our next adventure.
An Example of CRUD API To embark, let’s sketch out the pathways for our CRUD operations within the API. Each route will act as a gateway into our system, guiding requests to the precise actions needed to manage our data.
For us, these actions encompass creating, reading, updating, and deleting data.
Crafting API Routes As you venture into the domain of our API via the port (http://localhost:5000/), you may find yourself greeted by an error message.
When it comes to handling API requests, think of it as charting a map for your data’s journey. In this landscape, you wield powerful tools like app.get(), app.post(), app.put(), and app.delete() to define the paths data will traverse within your Express application, usually found in the index.js file.
Let’s focus on the basics first. Imagine GET requests as explorers seeking information. To guide them, we create routes using the app.get() function. Here’s a simple breakdown of how it works:
app.get('/', (req, res)
Let’s unpack the app.get() function further. It’s a key player in routing within Express, and it takes two important parameters.
Firstly, we define the path, which acts as the entry point for our GET requests. In the example provided, the path is specified as ‘/’. This means that when the root URL of our application is accessed, this route will be triggered.
The second parameter is a callback function, where the magic really happens. Within this function, we have access to two objects: req (short for request) and res (short for response).
The req object contains valuable information about the incoming request. This can include details such as the request query string, parameters, body, and HTTP headers. It’s like a package that holds all the data sent by the client.
On the other hand, the res object empowers us to craft our response. It’s our gateway to send back the information we want. We can set headers, specify status codes, and send data back to the client.
Here’s the complete code showcasing how it all comes together:
import express from 'express';
import bodyParser from 'body-parser'
const app = express();
const PORT = 5000;
app.use(bodyParser.json());
app.get('/', (req, res) => {
console.log('[GET ROUTE]');
res.send('HELLO FROM HOMEPAGE');
})
app.listen(PORT, () => console.log(`Server running on port: http://localhost:${PORT}`));
Returning to http://localhost:5000/ and refreshing the page should now yield a different outcome. Instead of encountering an error, you’ll find that the route we’ve just defined is now ready and waiting to handle any incoming GET requests to the root URL of our application. It’s a small but significant step towards building a robust API with Node.js and Express.
Let’s embark on the journey of crafting our own CRUD API, focusing on managing a set of users. This practical example mirrors real-world scenarios, making it an excellent starting point for understanding API development.
Here’s a breakdown of the API endpoints we’ll create:
- GET /users: Fetch all users from the database.
- POST /users: Add a new user to the database.
- GET /users/:id: Retrieve a specific user’s details.
- DELETE /users/:id: Remove a user from the database.
- PATCH /users/:id: Update a specific user’s information.
Firstly, let’s tackle the creation of the GET /users endpoint, which will retrieve a list of all users in JSON format. Follow these steps to set up the route:
- Create a new folder named routes to organize our route files.
- Inside the routes folder, create a new file named users.js.
- Write the code to configure the GET route within this users.js file.
This process lays the foundation for our API, allowing us to retrieve user data efficiently. Let’s dive into the code and bring this endpoint to life.
import express from 'express';
const router = express.Router();
// Mock database
const users = [
{
first_name: 'John',
last_name: 'Doe',
email: 'johndoe@example.com',
},
{
first_name: 'Alice',
last_name: 'Smith',
email: 'alicesmith@example.com',
},
];
// Getting the list of users from the mock database
router.get('/', (req, res) => {
res.send(users);
})
export default router
This code sets up an Express router to handle routes related to users. Let’s break it down:
Express Router Initialization:
- The
express.Router()
function is used to create a new router instance, which is stored in the variablerouter
.
- The
Mock Database:
- An array named
users
is defined, which serves as a mock database containing user objects. - Each user object has properties like
first_name
,last_name
, andemail
.
- An array named
Route Handling:
- A
GET
route is defined for the root path'/'
. - When a
GET
request is made to the root path, the callback function specified as the second argument is executed. - Inside the callback function,
res.send(users)
is used to send the list of users as the response.
- A
Export Router:
- The
router
instance is exported as the default export of the module. - This allows other parts of the application to import and use this router.
- The
Overall, this code defines a simple Express router with a single route for retrieving the list of users. When a GET
request is made to the root path, the router responds with the list of users stored in the mock database.
Save your changes in the users.js file. Then do the following in the index.js file:
import your user routes from user.js:
import userRoutes from './routes/users.js'
Use the app.use
method, and specify the path and router handler:
app.use('/users', userRoutes);
When a user navigates to http://localhost:5000/users, the router springs into action, serving as a gatekeeper to decide which routes should handle the incoming request.
Here’s the full code for the index.js file, orchestrating the flow of our Express application:
import express from 'express';
import bodyParser from 'body-parser'
const app = express();
import userRoutes from './routes/users.js'
const PORT = 5000;
app.use(bodyParser.json());
app.use('/users', userRoutes);
app.get('/', (req, res) => res.send('HELLO FROM HOMEPAGE'))
app.get('/', (req, res));
app.listen(PORT, () => console.log(`Server running on port: http://localhost:${PORT}`));
To test your API’s GET request, you have a couple of options: using a browser or a tool like Postman.
Here’s how to go about it:
Using a Browser:
- Copy your API URL, which in this case is http://localhost:5000/users.
- Paste this URL into the address bar of your browser.
- Hit Enter to send the GET request.
- You should then see the list of users displayed directly in your browser window.
Using Postman:
- Open Postman and create a new request.
- Select the GET method.
- Paste your API URL, http://localhost:5000/users, into the request URL field.
- Click on the “Send” button.
- Postman will execute the GET request, and you’ll see the response containing the list of users in the Postman console.
Both methods allow you to easily test your API’s GET request and view the resulting data. Choose whichever option suits your workflow best!
Create the POST /users Endpoint
Before we dive into creating the POST /users endpoint, we’ll need to install the UUID package, which generates unique identifiers. You can install it using the following command:
npm install uuid
Once you’ve installed the UUID package, we can proceed to define the route for handling POST requests to create new users in our API.
Here’s how to set it up:
- Create a new route file named users.js inside the routes folder (if you haven’t already).
- Import the necessary modules and dependencies, including Express and UUID.
- Define the route for handling POST requests to the /users endpoint.
- Parse the incoming request body to extract the user data.
- Generate a unique identifier for the new user.
- Save the user data to your mock database.
- Send an appropriate response back to the client.
Once you’ve set up the route, you can test it using either a browser or Postman, similar to how we tested the GET request earlier.
router.post('/', (req, res) => {
const user = req.body;
users.push({ ...user, id: uuidv4() });
res.send(`${user.first_name} has been added to the Database`);
})
This code adds a new route handler to the Express router for handling POST
requests to the root path '/'
. Let’s break it down:
Route Handling:
- The
router.post()
function defines a route handler forPOST
requests to the root path'/'
. - When a
POST
request is made to this path, the callback function specified as the second argument is executed.
- The
Request Body:
- Inside the callback function,
req.body
is used to access the data sent in the request body. - It assumes that the request body contains JSON data representing a user object.
- Inside the callback function,
Adding User to Mock Database:
- The user object extracted from the request body is pushed into the
users
array, which serves as the mock database. - The spread operator
{ ...user }
is used to create a new object with the properties of the user object received from the request. - Additionally, a unique
id
is assigned to the user object using a hypothetical functionuuidv4()
. - This function is not defined in the provided code snippet but is commonly used to generate unique identifiers.
- The user object extracted from the request body is pushed into the
Response:
- After adding the user to the mock database, a response is sent back to the client using
res.send()
. - The response contains a string message indicating that the user has been added to the database.
- After adding the user to the mock database, a response is sent back to the client using
Overall, this route handler allows clients to add new users to the mock database by sending POST
requests with user data in the request body. Upon successful addition, a confirmation message is sent back to the client.
Here is the full code so far
import express from 'express';
import { v4 as uuidv4 } from 'uuid';
const router = express.Router();
const users = [];
// Adding users to our mock database
router.post('/', (req, res) => {
const user = req.body;
users.push({ ...user, id: uuidv4() });
res.send(`${user.first_name} has been added to the Database`);
})
export default router
To test the POST request using Postman, follow these steps:
- Open Postman.
- Create a new request by opening a new request tab.
- Select “POST” from the list of available HTTP methods.
- In the URL field, enter the full URL where you want to send the POST request, which in this case would be http://localhost:5000/users.
- Click on the “Body” tab within the request window.
- Choose the format in which you want to send your POST data. For this example, select JSON.
- Enter the data you want to send in the request body. Make sure the format matches the structure expected by the server.
- Finally, click on the “Send” button to execute the POST request.
By following these steps, you can effectively test the POST request and verify that your API is correctly handling the creation of new users.
Indeed, upon successful addition of a new user via the POST request, you’ll receive a response confirming the action, such as “Daanny has been added to the database.”
To ensure that the user has been added as expected, you can make a GET request to retrieve the list of users. If everything went smoothly, you should see the new user included in the response.
It’s important to note that since we’re using a mock database and not persisting data to an actual database, any added user information will be lost when the server restarts. This setup is ideal for testing and development purposes but wouldn’t retain data across server sessions.
Create GET/users/:id endpoint
To create the GET /users/:id endpoint, which fetches specific user data based on a unique identifier (user ID), follow these steps:
- Define the route for handling GET requests to the /users/:id endpoint in your users.js route file.
- Extract the user ID from the request parameters.
- Query your mock database to find the user with the matching ID.
- If the user is found, send a response containing the user’s information.
- If the user is not found, send an appropriate error response indicating that the user was not found.
Once you’ve set up the endpoint, you can test it by making GET requests with different user IDs to retrieve individual user data.
This endpoint is crucial for scenarios where you need to fetch specific user information, such as displaying user profiles or retrieving user records from a database.
router.get('/:id', (req, res) => {
const { id } = req.params;
const foundUser = users.find((user) => user.id === id)
res.send(foundUser)
});
This code adds a new route handler to the Express router for handling GET
requests to a dynamic route /:id
. Let’s break it down:
Route Handling:
- The
router.get()
function defines a route handler forGET
requests to a dynamic route/:id
. - The
:id
in the route path represents a route parameter, which can be any value passed in the URL.
- The
Request Parameters:
- Inside the callback function,
req.params
is used to access the parameters passed in the URL. - Specifically,
req.params.id
is used to retrieve the value of theid
parameter from the URL.
- Inside the callback function,
Finding User by ID:
- The
find()
method is used to search for a user in theusers
array based on theirid
. - It iterates through the array and returns the first user object that matches the specified
id
.
- The
Response:
- After finding the user with the specified
id
, a response is sent back to the client usingres.send()
. - The response contains the user object (
foundUser
) that matches the specifiedid
.
- After finding the user with the specified
Overall, this route handler allows clients to retrieve a specific user from the mock database by sending GET
requests with the user’s ID included in the URL. Upon successful retrieval, the user object is sent back to the client.
To test the GET request for fetching user data, follow these steps:
- In Postman, navigate to the tab where you made the POST request to add a new user to the database.
- Verify that the POST request was successful by checking the response for the confirmation message, such as “Daanny has been added to the database.”
- Now, switch to the GET request tab.
- Make a GET request to the /users endpoint to retrieve the list of all users.
- Check the response to ensure that the newly added user is included in the list.
- Additionally, if you have implemented the GET /users/:id endpoint, you can test it by making a GET request with the specific user ID to retrieve individual user data.
By following these steps, you can effectively test the GET request and verify that your API is correctly retrieving user data from the database.
Create DELETE/users/:id endpoint
To implement the DELETE /users/:id endpoint for removing user data based on a provided user ID, follow these steps:
- Define the route for handling DELETE requests to the /users/:id endpoint in your users.js route file.
- Extract the user ID from the request parameters.
- Query your mock database to find the user with the matching ID.
- If the user is found, remove the user’s data from the database.
- Send a response indicating that the user has been successfully deleted.
- If the user is not found, send an appropriate error response indicating that the user was not found.
Here’s an example of how you can implement the code to delete a user from the database:
router.delete('/:id', (req, res) => {
const { id } = req.params;
users = users.filter((user) => user.id !== id)
res.send(`${id} deleted successfully from database`);
});
This code adds a new route handler to the Express router for handling DELETE
requests to a dynamic route /:id
. Let’s break it down:
Route Handling:
- The
router.delete()
function defines a route handler forDELETE
requests to a dynamic route/:id
. - The
:id
in the route path represents a route parameter, which can be any value passed in the URL.
- The
Request Parameters:
- Inside the callback function,
req.params
is used to access the parameters passed in the URL. - Specifically,
req.params.id
is used to retrieve the value of theid
parameter from the URL.
- Inside the callback function,
Filtering Users:
- The
filter()
method is used to create a new array of users excluding the user with the specifiedid
. - It iterates through the
users
array and removes the user object that matches the specifiedid
.
- The
Response:
- After filtering out the user with the specified
id
, a response is sent back to the client usingres.send()
. - The response contains a string message indicating that the user with the specified
id
has been deleted successfully from the database.
- After filtering out the user with the specified
Overall, this route handler allows clients to delete a specific user from the mock database by sending DELETE
requests with the user’s ID included in the URL. Upon successful deletion, a confirmation message is sent back to the client.
To test the DELETE request for removing a user from the database using Postman, follow these steps:
- Open Postman.
- Create a new request by opening a new request tab.
- Select “DELETE” from the list of available HTTP methods.
- In the URL field, enter the URL containing the ID of the user you want to delete. The URL should be in the format http://localhost:5000/users/:id, where “:id” is the unique identifier of the user you wish to delete. If you don’t have a user in your database, you’ll need to create one first and then copy the ID.
- Click on the “Send” button to execute the DELETE request.
- Postman will send the request to the server, and if successful, you’ll receive a response indicating that the user has been deleted.
By following these steps, you can effectively test the DELETE request and verify that your API is correctly removing user data from the database.
Create PATCH /users/:id endpoint
To create the PATCH /users/:id endpoint for making partial modifications to user data based on a provided user ID, follow these steps:
- Define the route for handling PATCH requests to the /users/:id endpoint in your users.js route file.
- Extract the user ID from the request parameters.
- Query your mock database to find the user with the matching ID.
- If the user is found, update the specified fields with the new data provided in the request body.
- Send a response indicating that the user has been successfully updated.
- If the user is not found, send an appropriate error response indicating that the user was not found.
Here’s an example of how you can implement the code to handle PATCH requests for updating user data:
router.patch('/:id', (req, res) => {
const { id } = req.params;
const { first_name, last_name, email} = req.body;
const user = users.find((user) => user.id === id)
if(first_name) user.first_name = first_name;
if(last_name) user.last_name = last_name;
if(email) user.email = email;
res.send(`User with the ${id} has been updated`)
});
This code adds a new route handler to the Express router for handling PATCH
requests to a dynamic route /:id
. Let’s break it down:
Route Handling:
- The
router.patch()
function defines a route handler forPATCH
requests to a dynamic route/:id
. - The
:id
in the route path represents a route parameter, which can be any value passed in the URL.
- The
Request Parameters and Body:
- Inside the callback function,
req.params
is used to access the parameters passed in the URL, specifically theid
. req.body
is used to access the data sent in the request body. It is assumed that the request body contains JSON data representing the updated user fields (first_name
,last_name
,email
).
- Inside the callback function,
Finding User by ID:
- The
find()
method is used to search for a user in theusers
array based on theirid
. - It retrieves the user object that matches the specified
id
.
- The
Updating User Fields:
- If the
first_name
,last_name
, oremail
fields are present in the request body, the corresponding fields of the user object are updated with the new values. - This allows clients to partially update user information by sending only the fields they want to update.
- If the
Response:
- After updating the user object, a response is sent back to the client using
res.send()
. - The response contains a string message indicating that the user with the specified
id
has been updated successfully.
- After updating the user object, a response is sent back to the client using
Overall, this route handler allows clients to update specific user information in the mock database by sending PATCH
requests with the user’s ID included in the URL and the updated fields in the request body. Upon successful update, a confirmation message is sent back to the client.
To test the PATCH request for updating user data using Postman, follow these steps:
- Open Postman.
- Create a new request by opening a new request tab.
- Select “PATCH” from the list of available HTTP methods.
- In the URL field, enter the URL containing the ID of the user you want to update. The URL should be in the format http://localhost:5000/users/:id, where “:id” is the unique identifier of the user you wish to update. If you don’t have a user in your database, you’ll need to create one first and then copy the ID.
- Click on the “Body” tab within the request window.
- Choose the format in which you want to send your PATCH data, such as JSON.
- Enter the data you want to send in the request body. This data should only include the specific changes you want to make to the resource, such as updating the firstName, lastName, or email fields.
- Finally, click the “Send” button. Postman will send the PATCH request to the specified URL with the provided data.
By following these steps, you can effectively test the PATCH request and verify that your API is correctly updating user data in the database.
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.