• Building Your First REST API with Node.js and Express

  • Learn to build a complete REST API from scratch using Node.js and Express. Includes CRUD operations, error handling, and testing best practices.

Building Your First REST API with Node.js and Express

Building Your First REST API with Node.js and Express

REST APIs are the backbone of modern web applications. At SwedTech Academy, we teach you to build production-ready APIs from day one.


What is a REST API?

REST (Representational State Transfer) is an architectural style for building web services. A REST API allows applications to communicate over HTTP using standard methods like GET, POST, PUT, and DELETE.


Setting Up Your Project

First, initialize a Node.js project and install Express:

mkdir task-api && cd task-api
npm init -y
npm install express

Building the Task API

Here's a complete example of a simple Task API with full CRUD operations:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

let tasks = [
  { id: 1, title: 'Learn Node.js', completed: false },
  { id: 2, title: 'Build REST API', completed: false }
];

// Get all tasks
app.get('/api/tasks', (req, res) => {
  res.json(tasks);
});

// Get single task
app.get('/api/tasks/:id', (req, res) => {
  const task = tasks.find(t => t.id === parseInt(req.params.id));
  if (!task) return res.status(404).json({ error: 'Task not found' });
  res.json(task);
});

// Create new task
app.post('/api/tasks', (req, res) => {
  const newTask = {
    id: tasks.length + 1,
    title: req.body.title,
    completed: false
  };
  tasks.push(newTask);
  res.status(201).json(newTask);
});

// Update task
app.put('/api/tasks/:id', (req, res) => {
  const task = tasks.find(t => t.id === parseInt(req.params.id));
  if (!task) return res.status(404).json({ error: 'Task not found' });
  
  task.title = req.body.title || task.title;
  task.completed = req.body.completed !== undefined ? req.body.completed : task.completed;
  
  res.json(task);
});

// Delete task
app.delete('/api/tasks/:id', (req, res) => {
  const index = tasks.findIndex(t => t.id === parseInt(req.params.id));
  if (index === -1) return res.status(404).json({ error: 'Task not found' });
  
  tasks.splice(index, 1);
  res.json({ message: 'Task deleted successfully' });
});

app.listen(PORT, () => {
  console.log(`Task API running on http://localhost:${PORT}`);
});

Error Handling

Add proper error handling:

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({ error: 'Route not found' });
});

Testing Your API

Use these tools to test:

  1. Postman: Visual API testing
  2. cURL: Command-line testing
  3. Thunder Client: VS Code extension

Example cURL commands:

# GET all tasks
curl http://localhost:3000/api/tasks

# POST new task
curl -X POST http://localhost:3000/api/tasks \
  -H "Content-Type: application/json" \
  -d '{"title":"Learn Express.js"}'

# PUT update task
curl -X PUT http://localhost:3000/api/tasks/1 \
  -H "Content-Type: application/json" \
  -d '{"completed":true}'

# DELETE task
curl -X DELETE http://localhost:3000/api/tasks/1

Best Practices

  1. Use environment variables: Store configuration securely
  2. Validate input: Check data before processing
  3. Use proper status codes: 200, 201, 400, 404, 500, etc.
  4. Add middleware: Authentication, logging, CORS
  5. Handle errors gracefully: Informative error messages
  6. Version your API: /api/v1/tasks

Next Steps

Now that you've built your first API, consider:

  • Adding a database (MongoDB, PostgreSQL)
  • Implementing authentication (JWT)
  • Adding validation (Joi, express-validator)
  • Documentation (Swagger)
  • Testing (Jest, Mocha)

Master Backend Development at SwedTech Academy

Building APIs is a fundamental skill for full-stack developers. In our Full-Stack Development course, you'll learn:

  • Advanced Node.js and Express patterns
  • Database design and integration
  • Authentication and authorization
  • API security best practices
  • Deployment strategies

Ready to become a full-stack developer? Join SwedTech Academy and build production-ready applications!

Keywords: REST API, Node.js tutorial, Express.js, backend development, API development, learn Node.js, SwedTech Academy
Want to know more?