Skip to Content

How do I use REST APIs?

With the rise of mobile applications and JavaScript frameworks, REST (REpresentational State Transfer) APIs have become the most common way for web services to expose functionality to application developers. Whether you’re fetching data from a database or executing complex application logic, REST APIs provide a simple interface to complete tasks programmatically.

What is a REST API?

A REST API is an application programming interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. REST, or REpresentational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other.

REST-compliant systems, often called RESTful systems, are characterized by how they are stateless and separate the concerns of client and server. We will go into what this means and why it is desirable later on.

Key Features of REST APIs

  • Client–server – A REST API separates the user interface concerns from the data storage concerns. The server manages data and state, and the client handles the UI and application.
  • Stateless – Each request from client to server must contain all of the necessary information to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
  • Cacheable – REST responses must define themselves as cacheable or not to prevent clients from reusing stale data that may result in inconsistent state.
  • Uniform interface – Using standardized HTTP methods to perform operations on resources like GET, POST, PUT and DELETE.
  • Layered system – REST allows you to use a layered system architecture where you deploy APIs on server A, forward requests to server B, and return the response back to the client via server A. The client doesn’t need to know about the layering happening behind the scenes.

The REST architectural style allows for many benefits that make REST APIs extremely effective:

  • Improved performance by reducing calls over the network due to caching
  • Scalability as REST is stateless so there is no stored context between requests
  • Simpler configuration because no state is stored on the server between requests
  • Easy to expose databases CRUD (create, read, update, delete) operations

Common HTTP methods used in REST APIs

REST APIs communicate via HTTP requests to perform standard operations related to resources. The most common HTTP methods include:

GET

A GET request is used to retrieve a resource from a server. The requested information is part of the URL called a query string. Performing a GET request against a resource URL should not change the resource state.

POST

A POST request is used to create a new resource or trigger an action. Unlike GET, any information sent to the server is included in the request body rather than the URL. This is useful for operations that deal with sensitive data like passwords that you don’t want exposed in your URL.

PUT

A PUT request is used to update an existing resource or create a resource if it doesn’t already exist. The full updated resource data is contained in the request body.

DELETE

A DELETE request removes the specified resource.

What does a REST API request look like?

REST APIs expose various HTTP endpoints (URLs) that provide access to the full capabilities of an application or service.

A REST API request uses a standard URL structure that contains the protocol (HTTPS), followed by the domain, path, and query string:

https://api.example.com/v1/orders?status=open

  • HTTPS – Use HTTPS for secure communication over TLS
  • api.example.com – The domain
  • /v1/orders – The path to the resource
  • ?status=open – An optional query string to filter results

The path usually contains the API version and the name of the resource you are accessing. Then as we’ll see, the HTTP method will indicate the operation to perform.

Example GET Request

Let’s look at an example request to retrieve a list of open orders, with some common headers:

“`
GET /v1/orders?status=open HTTP/1.1
Host: api.example.com
Accept: application/json
“`

This performs a GET request against the /v1/orders path, filtering for status=open and specifying that we want a JSON response via the Accept header.

The API would return a JSON response containing the list of open orders:

“`json
HTTP/1.1 200 OK
Content-Type: application/json

[
{
“id”: “order1”,
“total”: 39.99,
“status”: “open”
},
{
“id”: “order2”,
“total”: 49.99,
“status”: “open”
}
]
“`

The 200 OK status indicates the request succeeded, with the JSON data containing the orders array.

How to work with REST API authentication and authorization

Most APIs require authentication and authorization to access protected resources. There are several common methods used:

Basic Authentication

The client provides a username and password that gets encoded and sent in an Authorization header on every request. The credentials are stored on the client side.

“`
Authorization: Basic encodedcredentials
“`

Bearer Authentication / Token Authorization

The client obtains a temporary access token, usually via a POST request to an authorization API with client credentials. The access token gets sent in an Authorization header on every request.

“`
Authorization: Bearer
“`

API Keys

API keys are unique identifiers that are included on every request, either as a parameter or custom header. API keys are used to identify the client and may have restrictions.

“`
GET /v1/orders?api_key=
“`

“`
X-API-Key:
“`

OAuth 2.0 Authorization

OAuth 2.0 provides authorization flows for web and desktop applications, mobile devices, etc. It enables delegated authorization where a user grants access to their data without exposing credentials. Common OAuth 2.0 grants include authorization code, implicit, resource owner password credentials, and client credentials.

How to send data in a REST API request

The two main ways to send data in an API request are through query parameters or the request body.

Query Parameters

Query parameters are key/value pairs included along with the resource path in the URL:

“`
/v1/orders?status=open&limit=20
“`

This provides filtering and pagination options when retrieving resources.

Request Body

The request body is used when creating or updating resources with a POST, PUT, or PATCH request. The body contains a data payload in formats like JSON:

“`
POST /v1/orders HTTP/1.1
Content-Type: application/json

{
“item”: “Product Name”,
“amount”: 39.99
}
“`

Sensitive data and larger payloads should be sent in the request body rather than query params.

Common status codes in REST API responses

REST APIs use standard HTTP status codes to indicate the result of a request. Common status codes include:

Status Code Description
200 OK The request succeeded
201 Created Resource was successfully created in response to POST request
400 Bad Request The request failed, such as invalid parameters
401 Unauthorized Authentication failed or user does not have permissions
403 Forbidden Access to the specified resource is forbidden
404 Not Found The resource does not exist
500 Internal Server Error The server encountered an unexpected error

The response status provides quick insight into the result, while the response body contains more details about the request outcome.

How to test REST APIs

There are several techniques for testing REST APIs during development:

API testing with Postman

Postman is a popular GUI-based tool for testing APIs. You can configure requests, save collections of test cases, set up environments for different endpoints, run automated tests, and more. It also generates sample code snippets.

cURL

cURL provides a simple command line tool for executing API requests and inspecting responses. It’s easy to test APIs right from your terminal with cURL.

Writing automated tests

You can write automated integration tests for your API endpoints using frameworks like Mocha, Jest, RSpec, pytest, etc. These provide validation of responses and help prevent regressions.

Logging

Enable request and response logging through middleware in your API to log details like headers, parameters, response codes, and performance for each call. Logging provides visibility into API usage.

API mocking

Mock the expected interfaces of services that an API depends on for faster testing without needing real dependencies in place. This is great for testing in isolation.

API documentation

Generate API documentation using tools like Swagger / OpenAPI Specification to provide interactive documentation of endpoints that can also be used to mock responses and test the API.

Best practices for REST API error handling

Properly handling errors from a REST API helps create a more robust service for developers. Here are some best practices for REST API error handling:

– Use appropriate HTTP status codes that match the error condition
– Include error details in the response body, not just the status code
– Follow a consistent error response format, like providing an error code, message, and optional details field
– Document all potential error codes and messages in your API documentation
– Handle validation errors gracefully and return understandable validation problems
– Avoid revealing sensitive error details to clients that could expose security vulnerabilities
– Log errors on the server for debugging purposes but only return error information safe for clients
– Set useful Cache-Control headers when returning error responses
– Use service-specific error codes if needed to differentiate error conditions on the same endpoint
– Implement retries and exponential backoff for handling transient errors
– Return throttling information if API request rate limits are exceeded

Following standards for REST API error handling will ensure your API provides helpful feedback to developers when things go wrong.

Should I use REST or GraphQL?

REST and GraphQL are two common API design paradigms. Here are some key factors to consider when choosing between REST and GraphQL for your API:

REST

– Better for strict resource-based APIs
– More widespread usage and tooling support
– Simpler to design and understand
– Caching is built-in and standardized
– Easy to version APIs over time

GraphQL

– Allows clients to specify data requirements, avoiding over or under-fetching
– Single endpoint instead of multiple endpoints
– Strong typing and schema
– Easier to aggregate data from multiple sources
– Built-in documentation
– No versioning required

GraphQL is well-suited for applications that need to query multiple types of objects or aggregate data from various sources. REST works better for simpler APIs focused on accessing and manipulating resources.

Also consider team experience, availability of client libraries, and how comfortable you are defining a schema if using GraphQL. Try mocking prototyping the API using both techniques to see which approach better meets your needs.

Conclusion

REST APIs provide a simple, scalable approach to integrating systems using web technologies. Core concepts like HTTP methods, URIs, resources, and standard headers make REST a great choice for most APIs. While alternate approaches like GraphQL exist, REST is still the most common style for web APIs. Following REST principles and style guidelines results in an API that is easy to test, maintain, and consume from any language.