Building RESTful APIs

This issue will explore the fundamentals of building JSON/RESTful APIs, outline their benefits, and provide best practices and code examples to help you design APIs that are both efficient and easy to integrate.

In partnership with

Hello “👋

Welcome to another week, another opportunity to become a Great Backend Engineer.

Today’s issue is brought to you by Masteringbackend → A great resource for backend engineers. We offer next-level backend engineering training and exclusive resources.

Before we get started, I have a few announcements:

I have a special gift for you: You will love this one.

The ultimate “Land Your Dream Job” Challenge is here.

We are launching the ultimate guide to land your dream job in any programming language you choose. We are starting with the Python Programming language.

Land your dream Python Job in 90 days by shipping 30 Python projects in 30 days by completing our daily tasks.

It’s a cohort-based and project-focused challenge where you will be challenged to build 30 Python projects in 30 days.

Here are what you will get:

  • Ship 30+ Python backend projects in 30 days.

  • Instant Access to all 30+ videos

  • Access to data structure and algorithm interview kits.

  • Access our Complete Backend Job Preparation kits (Resume, Cover letter reviews, mock interviews, and job placements).

  • Join & learn from a thriving community of helpful students & alumni from top companies.

Limited Access. First 400 students at $54 others at $100 (We have only 120 slots left.)

Reply “Challenge” and I will send you a link to reserve your spot.

Check out our sponsor for this episode:

Writer RAG tool: build production-ready RAG apps in minutes

  • Writer RAG Tool: build production-ready RAG apps in minutes with simple API calls.

  • Knowledge Graph integration for intelligent data retrieval and AI-powered interactions.

  • Streamlined full-stack platform eliminates complex setups for scalable, accurate AI workflows.

In the last newsletter issue, we discussed How Server-Sent Events (SSE) Work and explained everything you need to know about them. Most importantly, we explored how Server-Sent Events (SSE) works.

Let’s deep dive into Building a RESTful API today and learn the intricacies of building an API, including Pagination, Rate Limiting, Idempotency, HATEOAS, Error Handling, etc. We will cover these topics in each newsletter issue. But for today, let’s look at how to build a simple RESTful/JSON API using Express.js.

Understanding the Fundamentals

What Is REST?

REST is an architectural style that defines a set of constraints and principles for building distributed systems. At its core, REST emphasizes:

  • Statelessness: Each request from a client must contain all the necessary information for the server to process it. The server does not store client context between requests, enabling scalability and reliability.

  • Resource Orientation: Resources (such as users, products, or orders) are identified by unique URLs. Operations on these resources are performed using standard HTTP methods (GET, POST, PUT, DELETE).

  • Uniform Interface: A consistent interface simplifies the interaction between clients and servers, making APIs easier to use and understand.

Why JSON?

JSON is a lightweight data interchange format known for its simplicity and readability. Its key attributes include:

  • Ease of Use: JSON's key-value pair structure is straightforward and intuitive, making it accessible to both humans and machines.

  • Lightweight: Its minimal syntax reduces payload size, leading to faster data transmission.

  • Language Agnostic: Almost every modern programming language supports JSON, ensuring seamless integration across diverse systems.

By leveraging JSON as the medium for data exchange, RESTful APIs become easier to work with and integrate, helping you to build interconnected systems more efficiently.

Key Principles in Building APIs

When designing and implementing a JSON/RESTful API, consider the following architectural constraints and design principles:

Resource Identification and Naming Conventions

  • Clear Endpoints: Use meaningful, pluralized nouns to represent collections (e.g., /users, /orders) and singular nouns for individual resources (e.g., /users/123).

  • Consistent URL Structure: Keep endpoint naming uniform and intuitive to facilitate discovery and ease of use.

Utilizing Standard HTTP Methods

RESTful APIs use standard HTTP methods to perform operations on resources:

  • GET: Retrieve resource representations.

  • POST: Create a new resource.

  • PUT/PATCH: Update an existing resource.

  • DELETE: Remove a resource.

Using these methods consistently aligns your API with RESTful principles and simplifies client-server interactions.

Embracing Statelessness

Every request must be self-contained:

  • Complete Information: Each request should carry all the data needed for processing, such as authentication tokens or query parameters.

  • Scalability: Stateless interactions make it easier to distribute load across multiple servers and handle high traffic volumes.

Data Representation and Format

  • JSON as the Data Format: JSON’s widespread acceptance makes it ideal for information interchange. It’s human-readable and easily parsed by client-side applications.

  • Schema and Versioning: Document the structure of your JSON payloads using schemas and maintain versioned endpoints (e.g., /api/v1/users) to manage changes without disrupting existing clients.

Error Handling and Status Codes

  • HTTP Status Codes: Use standard HTTP status codes to indicate the outcome of a request:

    • 200 OK for successful requests.

    • 201 Created for successful resource creation.

    • 400 Bad Request for malformed requests.

    • 404 Not Found when resources cannot be found.

    • 500 Internal Server Error for unexpected failures.

  • Structured Error Messages: Return JSON-formatted error messages that provide clear details about what went wrong.

Practical Example

This example will be built with Node.js because it is simple and easy to understand by everyone. For those, who do not write Node.js, you can use ChatGPT to cover the code to any programming language of your choice.

Below is a simple implementation using Node.js and Express to illustrate how you can build a JSON/RESTful API.

Step 1: Setting Up the Environment

First, create a new Node.js project and install Express:

mkdir json-rest-api
cd json-rest-api
npm init -y
npm install express

Step 2: Create the API Server

Create a file named app.js:

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

// Middleware to parse JSON bodies
app.use(express.json());

// Sample in-memory data store
let users = [
  { id: 1, name: 'Alice', email: '[email protected]' },
  { id: 2, name: 'Bob', email: '[email protected]' }
];

// GET /users - Retrieve all users
app.get('/users', (req, res) => {
  res.status(200).json(users);
});

// GET /users/:id - Retrieve a user by ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id, 10));
  if (user) {
    res.status(200).json(user);
  } else {
    res.status(404).json({ error: 'User not found' });
  }
});

// POST /users - Create a new user
app.post('/users', (req, res) => {
  const newUser = {
    id: Date.now(),
    name: req.body.name,
    email: req.body.email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT /users/:id - Update an existing user
app.put('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id, 10));
  if (userIndex !== -1) {
    users[userIndex] = { ...users[userIndex], ...req.body };
    res.status(200).json(users[userIndex]);
  } else {
    res.status(404).json({ error: 'User not found' });
  }
});

// DELETE /users/:id - Delete a user
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id, 10));
  if (userIndex !== -1) {
    const deletedUser = users.splice(userIndex, 1);
    res.status(200).json({ message: 'User deleted', user: deletedUser });
  } else {
    res.status(404).json({ error: 'User not found' });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`API running on http://localhost:${PORT}`));

This is a simple example of a demo RESTful where we are using an in-memory array storage mechanism instead of a database. Every other action is about manipulating the array to get results and convert them to JSON.

Benefits of Building JSON/RESTful APIs

  • Scalability: Stateless interactions allow the API to scale horizontally across multiple servers.

  • Maintainability: Clear separation of concerns and adherence to REST principles makes the API easier to maintain.

  • Integration: Standardized protocols and data formats ensure seamless integration with other systems and services.

  • Performance: Lightweight JSON reduces data overhead, leading to faster communication between client and server.

Building APIs involves more than just sending and receiving data. It’s about adhering to principles that ensure your API is scalable, maintainable, and easily integrated with other systems.

In the upcoming series, we will explore the following concepts Pagination, Rate Limiting, Idempotency, HATEOAS, and Error Handling, and expand the simple API above into a more robust and enterprise-ready API. Whether you're developing a simple application or a complex enterprise system, mastering these principles is essential for creating robust and future-proof APIs.

Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.

See you on Next Week.

Remember to start learning backend engineering from our courses:

Get a 50% discount on any of these courses. Reach out to me (Reply to this mail)

Top 5 Remote Backend Jobs this week

Here are the top 5 Backend Jobs you can apply to now.

👨‍💻 FaceUp
✍️ Node.js Backend Developer for FaceUp
đź“ŤRemote, Prague, Brno
đź’° Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 ROIVENUE
✍️ Full-stack Software Developer
đź“ŤRemote, Prague
đź’° Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Homepage
✍️ Backend Developer PHP
đź“ŤRemote, Worldwide
đź’° Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Monzo
✍️ Backend Engineer
đź“ŤRemote
đź’° Click on Apply for salary details
Click here to Apply for this role.

Want more Remote Backend Jobs? Visit GetBackendJobs.com

Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. ​The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. MB Video-Based Courses: Join 1000+ backend engineers who learn from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in backend development.

4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.

LAST WORD đź‘‹ 

How am I doing?

I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?

Hit reply and say hello - I'd love to hear from you!

Stay awesome,
Solomon

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.