Rest API Tutorial – A Complete Beginner’s Guide

Rest API Tutorial A Complete Beginner's Guide

Introduction

When building APIs, a RESTful API is one of the most common types of API to build. As with any technology, REST APIs can be built to serve straightforward use cases or be augmented to accommodate your most complex tasks. Regardless of what you are building, you’ve come here to figure out how to build a RESTful API, and that is precisely what we will do for this blog! By the end of this blog, you will be able to build a simple RESTful API with NodeJS that you can then expand on to fit your exact needs. Let’s get started by looking a bit further at precisely what a REST API is.

What is a REST API?

A REST (Representational State Transfer) API is a mechanism that allows different software applications to communicate with each other over the internet or local network. REST APIs follow specific rules and standards that enable applications and users to use HTTP requests to access and use data. The data sent and received by a REST API is generally in the JSON (JavaScript Object Notation) format. Data sent is a request, and the data received from the API call is called the response. Two main characteristics of RESTful APIs include:

  • Stateless Interactions: Each request from a client to a server must contain all the information needed to understand and process the request. The server does not store any session information about the client.
  • Uniform Interface: A REST API is designed to use standard HTTP methods and should be easy for any developer familiar with HTTP.
Learn More About Moesif Monitor and Analyze API Traffic with Moesif 14 day free trial. No credit card required. Try for Free

Why Use a REST API?

Many different types of APIs are available; however, RESTful APIs have become the go-to technology for almost every API in production today. This is not by chance but due to the simplicity and scalability of implementing and supporting REST technologies. The sheer amount of frameworks and technologies available to develop and support REST APIs alone is an excellent advantage over other popular API technologies. Let’s take a closer look at some of the benefits REST APIs can bring to developers.

  • Scalability: Due to their stateless nature, REST APIs can handle multiple types of calls, return different data formats, and even change structurally with the correct implementation of hypermedia.
  • Flexibility and Portability: Data is not tied to resources or methods, allowing more flexibility in its representation. This makes REST APIs suitable for different types of applications.
  • Independence: The separation between client and server allows for development across various parts of an application to coincide with less dependency on each other.

Key Features of REST APIs

REST APIs are built around six fundamental principles, some of which we have already touched on. Let’s take a closer look at each of the six principles below.

  1. Uniform Interface: This principle simplifies the architecture by establishing a standard communication method for clients and servers. This uniformity decouples clients from the server, allowing them to evolve independently as long as the interface remains consistent.

  2. Client-Server Separation: This separation of concerns enhances the portability of the user interface across multiple platforms and improves scalability by simplifying the server components. The client and the server operate independently, and changes on one side don’t directly impact the other.

  3. Statelessness: In a stateless architecture, each client request must contain all the necessary information for the server to process it. The server does not store any state about the client session on the server between requests, which simplifies design and increases reliability.

  4. Cacheable: Making responses cacheable can significantly improve performance by reducing the need for clients to fetch the same data repeatedly. Proper caching management helps ensure clients have up-to-date information and reduces the load on the server.

  5. Layered System: This principle allows an architecture to consist of hierarchical layers by restricting the behavior of components in each layer. Clients interact with a layer without knowing whether it’s the end server or an intermediary. This adds to the flexibility and scalability of the system.

  6. Code on Demand (optional): This constraint allows servers to extend or customize the functionality of a client by sending executable code (such as JavaScript). It can reduce the client’s complexity by offloading some functionality to the server, but it’s less common than the other constraints.

REST API Methods

Most developers are familiar with HTTP verbs/methods. Because of this, understanding REST API methods is quite simple to wrap your head around. REST APIs use the standard HTTP methods that developers (and most technical people) already know. With REST, each method is intended to perform specific functions:

  1. GET: This API method requests data from a specified resource. It should only retrieve data and should have no other effect.
  2. POST: This API method sends data to the server for creation. It is often used when uploading a file or submitting a completed web form.
  3. PUT: This API method updates all current representations of the target resource with the uploaded content.
  4. DELETE: As the name suggests, this method removes/deletes a specified resource.
  5. HEAD: Similar to GET, this method only transfers the status line and the header section.
  6. PATCH: This method applies partial modifications to a resource.

Each method corresponds to the CRUD (Create, Read, Update, Delete) operations in database management. Understanding each of the methods above is crucial for designing a RESTful API.

Advantages of Using REST APIs

REST APIs are known for their simplicity and flexibility, leveraging standard HTTP methods that are universally understood and easy to use. This universal approach to web communication allows for platform independence, making REST APIs compatible across different systems and languages. One of their key strengths is scalability, thanks to their stateless nature, which simplifies the server architecture by not requiring the server to maintain a session state. RESt APIs are also performant and efficient since responses can be effectively cached to minimize data transfers. Additionally, the portability and ease of integration of REST APIs facilitate the development of distributed systems and microservices, aided by massive communities and tooling support due to the widespread adoption of REST technologies.

Challenges When Using REST APIs

It’s also important to know that REST APIs come with specific challenges. The statelessness of REST can lead to larger requests since all necessary data must be included in each request. This also creates issues like data overfetching and underfetching, which can impact performance, as multiple requests may be needed to gather all data, or excessive data may be returned unnecessarily. Security concerns are a potential challenge, requiring proper implementation of authentication and data transfer security practices to keep data secure. Additionally, versioning of REST APIs can be complex, with changes potentially breaking backward compatibility. As REST APIs are scaled out, under high loads, REST APIs might experience performance bottlenecks due to HTTP/HTTPS overhead. Finally, the lack of a strict standard in REST implementation can lead to inconsistencies across different APIs.

How to Build a REST API

Now that we’ve reviewed all of the basics of what a REST API is and other fundamentals, it’s time to build one out. The example below shows a straightforward example of how to implement a REST API with NodeJS and Express. No actual CRUD operations are being done within the endpoints, but you can use this code to build those functionalities. Let’s start by setting up the environment, and then we will build out a few endpoints.

Step 1: Setting Up the Environment

  1. Install Node.js: Ensure you have Node.js installed. You can download it from nodejs.org.
  2. Initialize Your Project:
    • Create a directory for your project.
    • Navigate to this directory in your command line and run npm init to create a package.json file.

Step 2: Installing Express

Since this API project will use Express, we must install it within our project using npm. To do this, run npm install express in your project directory. Once the command is complete, Express will be installed and ready for us to use.

Step 3: Creating Your Server (server.js)

Now, we will begin to implement the actual API code. First, we will need to set up the basic infrastructure for our app. The first step is to create a file named server.js and add the following code:

const express = require('express');
const app = express();
app.use(express.json()); // This middleware is used to parse JSON bodies.

app.listen(3000, () => console.log('Server running on port 3000'));

In the above code, we are doing the following:

  • require('express'): Imports the Express module.
  • express(): Initializes a new Express application.
  • app.use(express.json()): Middleware to parse JSON request bodies.
  • app.listen(...): Starts the server on port 3000.

If we were to run the app right now, our service would be able to start, but we would have no API endpoints for users to use. Next, we will focus on implementing some endpoints that users can leverage.

Step 4: Implementing RESTful Endpoints

When creating APIs, having multiple endpoints that achieve various tasks makes sense. We need to use the HTTP methods we covered earlier for CRUD APIs (like we will implement here). The methods include GET, POST, PUT, and DELETE; each corresponds with a different CRUD operation. Let’s look at an example of each type of endpoint below. This code can be added and executed within our Express project after the app.use() statement.

GET Endpoint

First, we will implement the GET endpoint that fetches data from the server. In the code below, you can see the basic structure of such an endpoint.

app.get('/api/items', (req, res) => {
  res.send('List of items');
});

In the app.get(...) statement, we define our GET route. When a GET request is made to /api/items, the callback function is executed. In the case above, we return a string using res.send(). In a more functional endpoint, you’d likely go off to some resource, such as a database, and return some data.

POST Endpoint

Next, we will implement the POST endpoint. This endpoint will contain the logic to add new data to the server. In the code below, you can see the structure of such an endpoint.

app.post('/api/items', (req, res) => {
  const newItem = req.body; // Data sent in the request body.
  res.send(`Item added: ${newItem.name}`);
});

In the code above, the app.post(...) function handles POST requests. The req.body contains the data sent in the request and is sent back in the response. In a more functional endpoint, you’d likely see logic here that would write some data to a resource, such as a database. Once a new record is created, you may send back a boolean, such as created: true or the ID of the newly created entity.

PUT Endpoint

Now, we will create the PUT endpoint that will update existing data. In the code below, you can see the basic structure of a PUT endpoint.

app.put('/api/items/:id', (req, res) => {
  const itemId = req.params.id; // Access URL parameter.
  res.send(`Item with ID ${itemId} updated`);
});

In the code above, you’ll see that the app.put(...) handles the PUT requests. The ID of the resource to update is often passed as a query parameter or URI parameter. To access this, in the code, we use req.params.id to fetch the id parameter from the URL. In a real-life implementation, you’d make a database call to update the resource, with data usually found in the request body, and then return a Boolean stating whether the update was processed.

DELETE Endpoint

Lastly, we will show an example of a DELETE endpoint that removes data from the server. The code below will show a basic example of what a DELETE endpoint would look like in Express.

app.delete('/api/items/:id', (req, res) => {
  const itemId = req.params.id;
  res.send(`Item with ID ${itemId} deleted`);
});

As you can see in the above code, the app.delete(...) method handles the DELETE requests. Like PUT, it uses req.params.id to determine which item to delete. Also similar to our other endpoints, this would likely make a request out to a database to delete the specified resource in a more functional application.

Step 5: Testing Your API

With our API built, our next step is to get it up and running on our local system and test it with Postman. Let’s look at the individual steps required to deploy and test our endpoints, starting with starting up our Node.js server.

Set Up and Run Your API

You must ensure your Node.js server is running to access your API endpoints. Usually, you’ll get your server up and running by executing a command such as node server.js in a terminal (pointing at the root of your project).

Configure Postman

Next, we need to download and install Postman (or Insomnia, if you prefer) to issue requests to our endpoints to test them.

First, install Postman. If you don’t already have it installed, download it from the official website. Once installed, you’ll want to create a request. To do this, open Postman, click “New”, then “Request”, and save it to a new or existing collection.

Test Your API Endpoints

We will issue a request for each endpoint with the appropriate method selected, such as GET, POST, PUT, or DELETE. Below are the specifics for each method type. To test GET: Select ‘GET’, input your endpoint (e.g., http://localhost:3000/api/items){:target=”_blank” rel=”noopener noreferrer”}, and click “Send” to view the response. To test POST: Switch to ‘POST’, add your data in the request body in JSON format, and send the request to check the response. To test PUT and DELETE: Repeat similar steps for PUT (to update data) and DELETE (to remove data), ensuring to include the item ID in the endpoint URL.

Analyze Responses

As you test each endpoint, check that the responses for each request in Postman are correct. Successful operations typically return status codes like 200 (OK) or 201 (Created). If there are errors, use the response details and your server console logs to debug. If your endpoints are changing resources in a database, you’ll also want to check that the correct actions have occurred there.

Adding in API Analytics and Monetization

Building an API is only the start. Once your API endpoint is created, you’ll want to ensure that you monitor and analyze incoming traffic in addition to your API testing tool. Doing this lets you identify potential issues and security flaws and determine how your API design is used. These can all be crucial aspects in growing and supporting your APIs.

As your API platform grows, you may begin to focus on creating API products. By concentrating on API products, you’ll shift from simply building APIs to using them as a business tool and revenue stream. Much like a more formal product, an API product needs to be managed and likely will be monetized. Building revenue from your APIs can be a great way to expand your business’s bottom line.

With Moesif, you can achieve all of the above. Moesif can easily integrate through an SDK or plugin and be up and running in minutes. Once Moesif is integrated with your APIs, you’ll be able to explore charting and reporting to look at:

  • Live API traffic
  • Time-series reports inspecting usage
  • Conversion funnels
  • Retention reports
  • And much more…

Moesif also enables API monetization by allowing you to track usage and sync it to a billing provider like Stripe, Recurly, or Chargebee. Within minutes, integrate your APIs and begin billing customers for use. Moesif allows you to fine-tune what you want to bill users for and is highly customizable to suit the exact needs of your business.

Conclusion

With that, we have covered the basics of building a REST API. In this post, we used Node.js and Express to build some simple endpoints that can be expanded. Overall, the above code gives a good place to start when building out APIs for your applications.

Once you’ve built your APIs, you’ll likely want to start to analyze and monetize the usage of your APIs. In these cases, Moesif is a great tool to consider adding to your stack. Whether you’re building your first API or managing complex enterprise API portfolios, Moesif provides a platform that helps users develop better APIs for their users. To try out powerful analytics and monetization for yourself, sign up for a free trial of Moesif or chat with our team of API analytics and monetization experts to get started today!

Learn More About Moesif Monitor and Analyze API Traffic with Moesif 14 day free trial. No credit card required. Try for Free
Monitor REST APIs With Moesif Monitor REST APIs With Moesif

Monitor REST APIs With Moesif

Learn More