Express.js Crash Course: Create Simple APIs

Learn Express.js and create simple APIs step by step. Beginner-friendly guide to build RESTful servers using Node.js and Express.


Express.js is a lightweight, flexible, and powerful framework for Node.js that simplifies backend development. It allows developers to create servers, handle requests, and build APIs quickly without writing complex boilerplate code. In this crash course, we will guide you step by step to understand Express.js and create your first simple APIs.

Whether you’re new to backend development or looking to improve your Node.js skills, this guide will provide clear explanations, practical examples, and beginner-friendly steps.


1. What is Express.js?

Express.js is a Node.js framework that provides tools to create web servers and APIs. It is minimal but allows you to extend functionality using middleware and external libraries.

Key Features:

  • Minimal and flexible
  • Built on Node.js
  • Middleware support
  • Simplifies routing
  • Easy to create REST APIs

2. Why Use Express.js?

  • Simplified syntax: You don’t have to deal with Node.js boilerplate code.
  • Routing made easy: Define URL endpoints for different functionalities.
  • Middleware support: Handle tasks like logging, authentication, and error handling.
  • Community and ecosystem: Millions of packages via npm.

3. Installing Node.js and Express.js

Before using Express.js, you need Node.js installed.

Download Node.js LTS version from nodejs.org

Verify installation:

node -v
npm -v

Install Express in a project:

mkdir express-crash-course
cd express-crash-course
npm init -y
npm install express

4. Creating Your First Express Server

Create index.js:

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

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

Run it:

node index.js

Visit http://localhost:3000 to see your first Express server in action.


5. Understanding Routing in Express

Routing determines how your server responds to client requests.

app.get('/about', (req, res) => {
  res.send('About Page');
});

app.get('/contact', (req, res) => {
  res.send('Contact Page');
});

- GET: Fetch data

- POST: Send data

- PUT: Update data

- DELETE: Remove data


6. Handling Query Parameters and URL Parameters

Query parameters:

app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search results for: ${query}`);
});

URL parameters:

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});

7. Working with JSON Data

app.get('/api/user', (req, res) => {
  res.json({
    name: 'John Doe',
    role: 'Developer'
  });
});

8. Handling POST Requests

Install body-parser (optional for older Express versions):

npm install body-parser

Use it to parse JSON:

app.use(express.json());

app.post('/api/data', (req, res) => {
  const data = req.body;
  res.send(`Received data: ${JSON.stringify(data)}`);
});

Test using Postman or curl:

curl -X POST http://localhost:3000/api/data -H "Content-Type: application/json" -d '{"name":"Alice"}'

9. Middleware in Express

Middleware functions run before your route handlers.

app.use((req, res, next) => {
  console.log(`${req.method} request to ${req.url}`);
  next();
});

Third-party middleware:

  • cors for cross-origin requests
  • helmet for security headers

10. Serving Static Files

app.use(express.static('public'));

Create a public folder and add index.html. Access via http://localhost:3000/index.html.


11. Building a Simple REST API

let users = [];

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

app.post('/api/users', (req, res) => {
  users.push(req.body);
  res.json({ message: 'User added', users });
});

app.put('/api/users/:id', (req, res) => {
  const id = req.params.id;
  users[id] = req.body;
  res.json({ message: 'User updated', users });
});

app.delete('/api/users/:id', (req, res) => {
  const id = req.params.id;
  users.splice(id, 1);
  res.json({ message: 'User deleted', users });
});

12. Error Handling in Express

app.use((req, res, next) => {
  res.status(404).send('Route not found');
});

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Server error');
});

13. Organizing Your Project

  • Separate routes in /routes folder
  • Separate controllers in /controllers folder
  • Use environment variables (dotenv)
  • Use npm scripts for running dev server (nodemon)

14. Connecting to a Database (MongoDB Example)

npm install mongoose
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const UserSchema = new mongoose.Schema({
  name: String,
  role: String
});

const User = mongoose.model('User', UserSchema);

Perform CRUD operations via Mongoose models.


15. Best Practices

  • Use middleware for logging and security
  • Validate inputs (use express-validator)
  • Handle errors gracefully
  • Organize code into modules
  • Keep routes RESTful

16. Common Mistakes

  • Forgetting next() in middleware
  • Not parsing JSON request bodies
  • Hardcoding configuration instead of using environment variables
  • Mixing business logic with route handlers

17. Frequently Asked Questions (FAQs)

Q1: Is Express.js hard to learn?

No, if you know JavaScript basics, Express is beginner-friendly.

Q2: Can I use Express with MongoDB?

Yes, Express + Mongoose is a popular combination.

Q3: Do I need to know Node.js before Express?

Yes, a basic understanding of Node.js is recommended.

Q4: Can Express handle large apps?

Yes, many large applications use Express in production.


18. Final Thoughts

Express.js is a must-learn framework for backend JavaScript development. By following this crash course, you now know how to:

  • Create servers
  • Handle routes
  • Work with JSON and POST requests
  • Use middleware
  • Build simple REST APIs

The next step is to connect your API to a database, add authentication, and deploy it to a cloud service like Heroku, Vercel, or AWS. Practice building projects to solidify your understanding.


About the author

Prasun Barua
Prasun Barua is a graduate engineer in Electrical and Electronic Engineering with a passion for simplifying complex technical concepts for learners and professionals alike. He has authored numerous highly regarded books covering a wide range of elec…

Post a Comment