Back to blog
API DevelopmentSoftware Engineering

Building REST APIs

4 min read

Recently, I wrote an article about what APIs are, and how they connect us to the world around us every day. APIs are found everywhere - from ATMs, to weather apps, social media, even to restaurants. REST APIs, in particular, are a very common kind of web interface that is available to us today. But exactly what are REST APIs, and how can we build them?

Let’s Talk About REST

What are REST APIs, and why are they so important? Well, REST APIs are application programing interfaces (API) that follow the design principles of the REST architectural style. But what exactly is REST then?

The Representational State Transfer, also known as REST, is a set of architectural constraints that allow a variety of clients or applications to communicate with services. In doing so, they make sure those apps to run smoothly. Because they are so vital, it’s a good idea to design them properly and securely so that they function properly and don’t give you headaches. And especially as technology evolves, its important to design them in a way that keeps all the bad actors away!

What’s Necessary

REST APIs were built on a set of principles:

  • A client-server architecture
    • This involves separating concerns, with distinct clients, servers and other resources.
    • Example: A ReactJS Frontend connecting to a NodeJS Backend.
  • Stateless client-server communication
    • Every client request is independent of previous requests.
    • Example: Sending a login request with some sort of authentication token.
  • Cacheable data streamlining client-server
    • Responses made from the server can be cached for improvement of performance.
    • Example: Caching API responses for information that doesn’t change too often, like a weather updates.
  • A layered system organizing each type of server
    • Components are independent and can be replaced without impacting the system.
  • Code-on-demand to send executable code from the server
    • Servers can extend client functionality

Lets Build a REST API

Before creating an API, you must first make sure to plan and map out the resources that you need and also define the tech stack that you would like to use. For example, if you were building a very simple and non complex API for a social media app similar to X, lets call it ‘Twitter’, we would want to map out resources such as Users and Tweets.

For this example, we are going to use NodeJS and Express for the development of the API, and if you even wanted to test this out, you might consider using a tool like Postman.

Defining Endpoints:

When defining endpoints, it’s important to utilize CRUD Operations (Create, Read, Update, Delete) with RESTful routes:

  • POST /tweet to post a new tweet
  • GET /tweets to get all tweets
  • GET /tweets/:id to get a specific users tweets
  • GET /users/:id to find specific information for a user
  • PUT /tweet/:id to update a specific tweet
  • DELETE /tweet/:id to delete a specific tweet

Create the API (with code)

// app.js

import express from 'express';

const app = express();
app.use(express.json()); // Used to parse JSON request bodies

app.get('/', (req, res) => {
    res.send('Welcome to our API!');
})

app.get('/tweets', (req, res) => {
    res.send([
	    { id: 1, tweet: 'Make this year a great one!', user: 'John Doe' },
	    { id: 2, tweet: 'Hope you learned about APIs!', user: 'Godwin' }
    ]);
})

app.post('/tweet', (req, res) => {
    // Handle your backend logic here and perform a Create operation
})

app.listen(3000, () => {
    console.log('Server is up and running on the PORT 3000');
})

Best Practices

In terms of creating and iterating on APIs, I feel like everyone will have their own definition of good practices, and it may vary depending on the programming language as well. But these steps right here are universal best practices that you want to keep in mind as you build more complex APIs.

  • Versioning - Be sure to use version numbers in the URL for backwards compatibility (don’t overlook this).
  • Error Handling - Return meaningful error messages so that debugging is not a pain when you run into any issues.
  • Documentation - Be sure to document the API very well so that, again, debugging is not a pain when you run into any issues.
  • Pagination - Use a limit for large amounts of data to improve performance!

Small Lesson on HTTP Status Codes

When working with RESTful services, understanding HTTP status codes is really crucial. These status codes are sent back along with the response of your API to communicate the outcome of the request. Here’s a quick cheatsheet for you:

  • 2xx: Success
    • 200 OK - The request was successful.
    • 201 Created - A resource was successfully created.
    • 204 No Content - A request was successful but returns no content.
  • 3xx: Redirection
    • 301 Moved Permanently - The request resources has been moved to a new URL.
  • 4xx: Client Error
    • 401 Unauthorized - A client is required to authenticate.
    • 403 Forbidden - A client is authenticated but does not have the necessary permissions.
    • 404 Not Found - A resource is not found.
  • 5xx: Server Error
    • 500 Internal Server Error - An error occurring on the server side.

Conclusion

Because APIs are used heavily in our day to day lives, it’s important to know how to build them as a developer. I hope you’re able to learn a bit from this article. As a next step, I encourage you to build you to build your own API and see how far you can go with it!