GICT knowledge base
How to create CRUD API with Node.js and Express – Beginner’s Guide
Published
So you want to learn how to make a CRUD API? Well, that’s great! It’s not as hard as it sounds. Let me show you how to do it step by step.
Many people think making APIs is super hard, but it’s really not. Once you understand the basics, you’ll be surprised how easy it is. We’re going to build something real that actually works. You don’t need to be a coding expert or anything like that. Just follow along, and I’ll explain everything in simple words. By the end of this, you’ll have your own working API that you can show to others. It’s actually pretty fun once you get started, and you’ll feel really good when you see it working. Trust me, if I can do it, you can too!
What is a CRUD API?
First, let’s talk about what CRUD means. CRUD stands for four basic things you can do with data:
- Create – Add new stuff to your data
- Read – Look at your data
- Update – Change stuff that’s already there
- Delete – Remove things you don’t want anymore
Now, an API is like a bridge. It lets different apps talk to each other. So a CRUD API is a bridge that lets you create, read, update, and delete data from somewhere else.
Think of it like this – if you have a list of books, a CRUD API would let you:
- Add a new book to the list
- Look at all the books
- Change a book’s info
- Remove a book from the list
Pretty simple, right?
Why Use NodeJS and Express?
NodeJS is really popular for making APIs. Here’s why:
- It’s fast
- Easy to learn
- Lots of people use it
- Good for beginners
- Works well with databases
Express is a tool that makes NodeJS even easier to use. It helps you build web apps and APIs quickly. Think of Express as a helper that does the hard work for you.
What You Need Before Starting
Before we start, you need a few things on your computer:
- NodeJS installed
- A code editor (like VS Code)
- Basic knowledge of JavaScript
- A terminal or command line
Don’t worry if you’re not an expert with these. You’ll learn as we go.
Setting Up Your Project
Let’s start by making a new folder for our project. Open your terminal and type:
mkdir my-crud-api cd my-crud-api
Now we need to start a new NodeJS project:
npm init -y
This makes a file called package.json. It keeps track of what tools we use in our project.
Next, we need to install Express:
npm install express
Great! Now we have everything we need to start.
Making Your First Server
Let’s make a simple server. Create a new file called server.js and add this code:
// Get the express tool
const express = require('express');
// Make a new app
const app = express();
// Set the port number
const PORT = 3000;
// Make the app understand JSON data
app.use(express.json());
// A simple test route
app.get('/', (req, res) => {
res.send('Hello! Your API is working!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Now run your server:
node server.js
Open your web browser and go to http://localhost:3000. You should see “Hello! Your API is working!”
Awesome! Your server is working.
Understanding Routes
Routes are like paths in your API. They tell your server what to do when someone visits different URLs.
In our example above, we made one route:
GET / – This shows a welcome message
For a CRUD API, we need four types of routes:
- GET – To read data
- POST – To create new data
- PUT – To update existing data
- DELETE – To remove data
Planning Our API
Let’s make an API for managing books. We’ll need these routes:
- GET /books – Get all books
- GET /books/:id – Get one book by ID
- POST /books – Add a new book
- PUT /books/:id – Update a book
- DELETE /books/:id – Delete a book
The :id part is special. It’s a parameter that changes based on which book we want.
Storing Data (Simple Way)
For now, we’ll store our books in a simple array. In real projects, you’d use a database, but this is easier to understand.
Add this to your server.js file after the express setup:
// Our fake database - just an array
let books = [
{ id: 1, title: 'Harry Potter', author: 'J.K. Rowling' },
{ id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien' },
{ id: 3, title: '1984', author: 'George Orwell' }
];
// Keep track of the next ID
let nextId = 4;
Reading Data (GET Routes)
Let’s make our first CRUD route. This one gets all books:
// GET all books
app.get('/books', (req, res) => {
res.json(books);
});
This route sends back all our books as JSON.
Now let’s make a route to get just one book:
// GET one book by ID
app.get('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const book = books.find(b => b.id === id);
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
res.json(book);
});
This route:
- Gets the ID from the URL
- Looks for a book with that ID
- Sends back the book if found
- Sends an error if not found
Creating Data (POST Route)
Now let’s add a route to create new books:
// POST - Create a new book
app.post('/books', (req, res) => {
const { title, author } = req.body;
// Check if we have all the info we need
if (!title || !author) {
return res.status(400).json({ error: 'Title and author are required' });
}
// Make a new book
const newBook = {
id: nextId++,
title: title,
author: author
};
// Add it to our array
books.push(newBook);
// Send back the new book
res.status(201).json(newBook);
});
This route:
- Gets the title and author from the request
- Checks if they’re there
- Makes a new book with a unique ID
- Adds it to our array
- Sends back the new book
Updating Data (PUT Route)
Let’s add a route to update existing books:
// PUT - Update a book
app.put('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const { title, author } = req.body;
// Find the book
const bookIndex = books.findIndex(b => b.id === id);
if (bookIndex === -1) {
return res.status(404).json({ error: 'Book not found' });
}
// Update the book
if (title) books[bookIndex].title = title;
if (author) books[bookIndex].author = author;
// Send back the updated book
res.json(books[bookIndex]);
});
This route:
- Gets the ID from the URL
- Finds the book in our array
- Updates the title and/or author if provided
- Sends back the updated book
Deleting Data (DELETE Route)
Finally, let’s add a route to delete books:
// DELETE - Remove a book
app.delete('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
// Find the book
const bookIndex = books.findIndex(b => b.id === id);
if (bookIndex === -1) {
return res.status(404).json({ error: 'Book not found' });
}
// Remove the book
const deletedBook = books.splice(bookIndex, 1)[0];
// Send back the deleted book
res.json(deletedBook);
});
This route:
- Gets the ID from the URL
- Finds the book in our array
- Removes it from the array
- Sends back the deleted book
Testing Your API
Now let’s test our API! You can use a tool like Postman, or just your browser for GET requests.
- Test GET all books: Open http://localhost:3000/books in your browser. You should see all three books.
- Test GET one book: Try http://localhost:3000/books/1. You should see just the Harry Potter book.
- Test POST (create): This is harder to test in a browser. You need a tool like Postman or curl. Send a POST request to http://localhost:3000/books with this JSON:
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
}
Test PUT (update): Send a PUT request to http://localhost:3000/books/1 with:
{
"title": "Harry Potter and the Philosopher's Stone"
}
Test DELETE: Send a DELETE request to http://localhost:3000/books/1.
Error Handling
Good APIs handle errors well. We already added some error handling, but let’s add more:
// Handle 404 errors
app.use('*', (req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// Handle other errors
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
Add these at the end of your file, before app.listen().
Making It Better
Here are some ways to make your API better:
- Add Validation: Check if the data is correct before saving it.
- Use a Real Database: Instead of an array, use MongoDB or PostgreSQL.
- Add Authentication: Make sure only the right people can use your API.
- Add Logging: Keep track of what happens in your API.
- Use Environment Variables: Don’t put sensitive info in your code.
Common Mistakes to Avoid
Here are some things that trip up beginners:
- Forgetting to parse JSON: Always use app.use(express.json())
- Not checking for errors: Always check if data exists before using it
- Wrong status codes: Use 200 for success, 404 for not found, 400 for bad requests
- Not handling edge cases: What if someone sends empty data?
- Forgetting to start the server: Don’t forget app.listen()
Complete Code
Here’s what your complete server.js file should look like:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
// Our fake database
let books = [
{ id: 1, title: 'Harry Potter', author: 'J.K. Rowling' },
{ id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien' },
{ id: 3, title: '1984', author: 'George Orwell' }
];
let nextId = 4;
// Routes
app.get('/', (req, res) => {
res.send('Hello! Your API is working!');
});
app.get('/books', (req, res) => {
res.json(books);
});
app.get('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const book = books.find(b => b.id === id);
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
res.json(book);
});
app.post('/books', (req, res) => {
const { title, author } = req.body;
if (!title || !author) {
return res.status(400).json({ error: 'Title and author are required' });
}
const newBook = {
id: nextId++,
title: title,
author: author
};
books.push(newBook);
res.status(201).json(newBook);
});
app.put('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const { title, author } = req.body;
const bookIndex = books.findIndex(b => b.id === id);
if (bookIndex === -1) {
return res.status(404).json({ error: 'Book not found' });
}
if (title) books[bookIndex].title = title;
if (author) books[bookIndex].author = author;
res.json(books[bookIndex]);
});
app.delete('/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const bookIndex = books.findIndex(b => b.id === id);
if (bookIndex === -1) {
return res.status(404).json({ error: 'Book not found' });
}
const deletedBook = books.splice(bookIndex, 1)[0];
res.json(deletedBook);
});
// Error handling
app.use('*', (req, res) => {
res.status(404).json({ error: 'Route not found' });
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
What’s Next?
Now that you know how to make a basic CRUD API, here are some next steps:
- Learn about databases: Try MongoDB or PostgreSQL
- Add user authentication: Learn about JWT tokens
- Deploy your API: Put it on Heroku or AWS
- Add more features: Search, filtering, pagination
- Learn about testing: Write tests for your API
- Study REST principles: Learn the proper way to design APIs
Final Tips
Making your first CRUD API is a big step! Here are some final tips:
- Start small: Don’t try to build everything at once
- Practice: Make different APIs for different things
- Read the docs: Express documentation is really helpful
- Join communities: Ask questions on Stack Overflow or Reddit
- Keep learning: There’s always more to learn
Well, that’s it! You now know how to make a basic CRUD API with NodeJS and Express. It might seem like a lot at first, but once you practice, it becomes much easier. The key is to start simple and build up from there.
Remember, every expert was once a beginner. Keep practicing, keep learning, and soon you’ll be making amazing APIs. Good luck with your coding journey!
Related guides
How to Add Redis Cache to Node.js Apps
Complete guide to adding Redis cache in Node.js apps. Learn setup, database query caching, session storage, and production tips with code examples.
Node.jsHow to Deploy Node.js Applications with Nginx
Learn how to deploy Node.js apps with Nginx reverse proxy. Complete step-by-step tutorial covering server setup, SSL certificates, PM2 process management, and production...
Node.jsHow to Delete Data in MongoDB Using Node.js
Master data deletion in MongoDB using Node.js with safe filters, bulk operations, soft deletes, and best practices for performance, security, and compliance.
Node.jsHow to Install Node.js and Pm2 in Ubuntu 20.04
Node.js is a popular javascript framework. Follow this tutorial to learn How to install node.js and PM2 on an Ubuntu operating system.
