What is a REST API?

August 4, 2022

Introduction

APIs are changing the way companies design, build, and implement software applications.

Monolithic architecture has given way to solutions based on loosely coupled microservices. Developers can focus on core functionalities while using different types of APIs to access and incorporate functions and features created by other specialists.

REST has quickly become one of the most popular architectural styles for creating web-based apps and services.

Find out how REST APIs work and use them to develop innovative business and customer-facing solutions.

Developing RESTful API.

REST API Definition

Representational State Transfer (REST) is a hybrid architectural style for developing network-based applications. REST defines a set of constraints (principles) that need to be applied to architectural elements (components, connectors, and data) and the relationship among those elements.

APIs that adhere to REST constraints are called REST or RESTful APIs.

REST API Constraints

REST has six (6) architectural constraints that serve as high-level guidelines for designing distributed software systems.

By applying REST constraints, developers can induce and improve the non-functional properties of a software system. These include:

  • Portability
  • Scalability
  • Visibility
  • Reliability
  • Network efficiency
  • User-perceived performance
  • Simplicity
  • Evolvability
  • Extensibility

Many HTTP APIs are advertised as RESTful even though they do not comply with all the formal REST constraints outlined in Roy Fielding’s dissertation. This has led to lively discussions in the developer community about what constitutes a truly RESTful API.

Developers typically refer to the Richardson Maturity Model to determine the level to which an API adheres to RESTful principles.

Client-Server Separation

In a client-server architecture, the client component uses a connector to send requests to a server component.

The server performs or rejects the requested service and sends a response to the client. A server continually listens to requests and typically serves multiple clients.

Client and server applications are not contingent on each other and can be developed, modified, or replaced independently.

This separation of concerns enhances the portability of a user interface, like a web browser, across multiple platforms and improves the scalability of server components, such as databases.

Stateless Communication

The server must understand each client request individually without deriving context or information from previous requests. This type of client-server communication, where the receiver does not retain the session state from previous requests, is called a stateless communication protocol.

Statelessness improves:

  • Visibility - The server does not need to look beyond a single request.
  • Reliability - The system can recover from failures more efficiently.
  • Scalability - Servers require fewer resources as there is no need to store prior session data.
  • Simplicity - It is no longer necessary to manage resources across multiple requests.

However, stateless protocols also inflate the number of client-server interactions and may increase per-interaction overhead. Client-side caching is used to mitigate this issue.

Caching

Client applications can cache server responses and reuse them for later requests to improve network efficiency and user-perceived performance.

Caching in a Content Delivery Network (CDN), device memory, or in a browser cache storage significantly reduces the number of client-server interactions.

Keep in mind that caching can decrease reliability as the cached data may differ from data obtained by sending a new request to the server.

Uniform Interface

The uniform interface is a fundamental constraint of the REST architectural style.

Server responses do not give clients access to a resource but a decoupled resource representation. For example, the client does not receive a database from the server but a JSON, HTML, or XML web document that represents the database records in the format outlined in the client request. 

The uniform interface is based on four principles:

  • Resource identification - To simplify and enhance the visibility of interactions, each resource within a system should have a unique URI. Resource representations must adhere to specific guidelines, including data formats, naming conventions, and link formats.
  • Resource manipulation through representations – The resource representation must contain enough data so that the client can modify or delete the resource’s state. Resources should be accessible and alterable through a common approach, like an HTTP method (i.e., POST, GET).
  • Self-descriptive messages - Each message should be self-descriptive and include enough information to describe how to process the message. Clients can obtain the necessary data by checking the semantics without knowing the application-specific data structure.
  • Hypermedia as the engine of application state (HATEOAS) - Clients send a message that includes a header, body, and query-string parameters to the resource URI. Services respond via response headers, body content, and response codes. In addition to the described process, the HATEOS principle states that (when necessary) the returned body (or header) hypertext needs to contain hyperlinks the client can use to dynamically discover all the available resources it needs.

Layered System

Deploying web services, data storage, and security logic in separate and hierarchical layers allows developers to impose limits on how these components interact.

Restricting the “knowledge” of a resource results in a less complex system with independent and controllable layers.

A layered system is essential for enforcing security policies in modern web architecture. It also improves scalability and enables resources to call multiple intermediary servers when generating a client response.

The messages between the client and target server should always be formatted and processed the same way, regardless of the layers between them. Additional layers should not affect client-server interactions.

Code On Demand (Optional)

The REST Code on Demand constraint is optional. REST allows client apps to extend functionality by downloading and executing widgets or scripts. For example, a merchant can use a payment processor’s widget to facilitate strong customer authentication.

However, code on demand also reduces visibility. It is left up to the developer to apply or disregard this constraint depending on the intended use case and context.

How Does REST API Work?

REST API providers typically supply exhaustive documentation that lists API endpoints and explains how to structure an API call.

The endpoint URL represents the resource location API users use to send requests and interact with resources.

Even though REST supports many communication protocols, the HTTP protocol has become a standard for most modern applications.

Client HTTP requests have 5 separate elements:

  • Verb − Defines the HTTP request method (i.e., GET, POST, DELETE, PUT, PATCH).
  • URI (Uniform Resource Identifier) − The URI identifies the resource on the server.
  • HTTP Version − Specifies the HTTP version (for example, v1 or v2).
  • Request Headers − An HTTP header is a name-value pair separated by a colon (:). Headers contain more information about the resource or the client sending the request. This may include the browser type, formats supported by the client, authorization, authentication methods, etc.
  • Request Body − The request message content in the specified data format.
REST API request elements.

HTTP responses consist of 4 elements:

  • Response Code/Resource Status − The response code indicates the status of the requested server resource. For example, response 200 implies that the request was successful, while the 415 error code suggests that the data format in the request message is not supported.
  • HTTP Version − Specifies the HTTP version.
  • Response Headers − The HTTP Response metadata. It can indicate if a message is cacheable or non-cacheable, server type, response data, content type, etc.
  • Response Body − The response message content (resource representation).
REST API response elements.

HTTP request methods, also called HTTP Verbs, enable clients to specify the type of action they want to perform on a given resource. Each method triggers a different process, but they can be grouped based on common features.

Safe HTTP methods, like GET or HEAD, prompt read-only operations that do not modify server resources. Verbs that allow clients to send the same request many times over without changing the server resource state are called idempotent verbs.

Frequently used RESTful HTTP methods include:

HTTP METHOD
(VERB)
DESCRIPTIONSAFEIDEMPOTENT
GETThe GET verb is used to retrieve a resource from a server. The data is only read and not modified.YesYes
HEADLike GET, HEAD retrieves a resource. However, the response only contains the resource status and header and does not return a body. It is used to check what a GET request might potentially return.YesYes
POSTUsed to send a request to create or update a server resource. POST requests are not cached and do not remain in the browser history.NoNo
PUTThe PUT verb replaces the existing representation of the target resource with newly uploaded content. Sending the same PUT request multiple times produces the same result.NoYes
DELETERemoves the specified resource.NoYes
PATCHMakes partial changes to an existing resource.NoNo
OPTIONSThe OPTIONS verb helps clients learn which communication options are associated with a resource.YesYes
TRACEPerforms a message loop-back test along the path to the target resource.YesYes

REST APIs support multiple formats for exchanging and storing data like JSON, XML, HTML, YAML, etc. This wide array of different data formats makes REST a popular architectural style for building public APIs.

What Is REST API Used For?

The REST architectural style allows software solutions to communicate regardless of their size and complexity. It supports several transfer protocols, with HTTP being the most common, and multiple data formats that are machine- and human-readable.

The ability to deploy and scale components independently makes RESTful APIs ideal for systems that serve large numbers of diverse clients, like web servers and web apps.

High-level REST API model.

With the capacity to enforce security, decrease latency, and encapsulate legacy systems, REST APIs can be applied to almost any use case. They are especially well-suited for:

REST API Examples

Some of the world’s largest brands use RESTful APIs to expose their services to other businesses and end-users. High-profile examples include:

Salesforce

The Salesforce REST API enables users to create, analyze, and modify customer data without accessing the Salesforce user interface.

Businesses can integrate Salesforce services into their applications and streamline business processes by sending HTTP requests to Salesforce API endpoints.

The different endpoints give client applications access and permission to operate on query results, metadata, records, and other resources.

The integration process is supported by comprehensive and user-friendly documentation. The REST API can be integrated with other Salesforce APIs and used to develop custom UIs for generating list views, actions, and dependent picklists.

Twitter

Twitter uses a series of API endpoints to expose a multitude of different services. Companies can use these endpoints to programmatically retrieve data users post on Twitter and data Twitter aggregates about its users.


Note: Twitter’s HTTP-based Web API does not strictly adhere to all six REST constraints.


The number of available endpoints and features on the Twitter API can make it challenging to determine which API endpoint is relevant for a specific use case. Twitter’s API allows organizations to: 

  • Track and react to posts, conversations, and perceptions surrounding a company, brand, or service.
  • Retrieve Tweets, Direct Messages, and other activities related to an account.
  • Resolve issues by reaching out to customers in real-time.
  • Track Return of Investment (ROI) on targeted marketing campaigns.
  • Curate and recommend content.
  • Analyze trends, customer preferences, and the competition’s marketing strategies.
  • Filter, retrieve, and analyze relevant Tweets.

Organizations can use vast amounts of real-time data to build applications for evaluating and even reacting to Tweets related to specific topics.

CCBill

The CCBill RESTful Transaction API allows merchants to access and utilize CCBill’s payment platform and charge customers with a payment token. Merchants can develop custom purchase flows without using CCBill’s hosted payment forms.

CCBill provides detailed API documentation that lists all the relevant API endpoints, resources, and query examples.

To streamline the implementation process, CCBill developed an Advanced Widget for automating payment token requests. The CCBill Advanced Widget also enables merchants to integrate with CCBill's 3DS vendor and incorporate strong customer authentication in their transactions.

Trello

Trello is a project management tool that provides a simple RESTful web API. Each type of API resource (e.g., Board, List, Card, Member, Action) has a unique URI with which client apps can interact.

Trello handles the authentication and authorization process, so that client apps do not have to store usernames or passwords. Apps temporarily delegate user authentication to Trello via an API key. The control, along with an API token, is returned to the user application once the user successfully signs in.

REST API Best Practices

Designing an API based on REST architectural constraints is challenging. Apply the following practices to ensure that an API is easy to view, read, and consume:

  1. Use the JSON data format for requests and responses - Most programming environments have the capacity to parse and generate JSON. Its linguistic structure also allows humans to read and understand JSON syntax easily.
  2. Apply standard API versioning - If the API service has multiple versions, ensure that the version number is included in the REST API URI. This streamlines the development process and ensures changes do not break client applications.
  3. Do not use verbs in endpoint paths - Since HTTP request methods already contain verbs, inserting them in endpoint paths is inefficient. Only use nouns in endpoint URIs.
  4. Use standard HTTP status error codes and messages - Using standard HTTP error codes like the 503 service unavailable error or the 403 error code helps API users instantly understand what type of error occurred. The error message should contain enough information to facilitate troubleshooting but also prevent potential attackers from exploiting the error message content.
HTTP response status codes and messages.
  1. Design consistent and logical endpoints - Define and group endpoints to reflect the logical structure and hierarchy of database objects. However, avoid revealing the exact database structure as attackers may be able to exploit this information.
  2. Employ good security practices - A security breach may cause an irreparable loss of revenue and reputation. Organizations that expose their services using APIs must develop strict security procedures, train staff, and implement advanced technical solutions:
    • Get an SSL Certificate.
    • Prevent access from unknown IP addresses and domains.
    • Block unusually large payloads.
    • Log all requests and thoroughly investigate failed requests.
    • Strictly define user roles and restrict user access according to the principles of least privilege.
  3. Keep database load and response times under check - API databases grow over time, increasing the time it takes to search and retrieve data. Use pagination, sorting, and filtered endpoints to streamline searches and data retrieval from REST API collections.
  4. Allow client-side caching - Caching reduces latency, bandwidth, and server loads. Add a <strong><em>Cache-Control</em></strong> directive to response headers to explicitly allow client-side caching.
  5. Ensure that the API documentation is comprehensive and accurate - API documentation is a developer’s principal resource for implementing a third-party API solution. The documentation should convey:
    • The relevant API endpoints.
    • Instructions on how to structure an API request (including multiple HTTP methods and examples of acceptable data formats).
    • Examples of expected responses.
    • List of potential error codes and messages.

Applying these recommendations enables API users to consume your RESTful API solution easily and safely.

Conclusion

You know how RESTful systems work, their architectural constraints, and the types of projects they are best suited for.

New REST API developers need to work hard to come up with a working implementation. API development is a best practice-driven approach, and articles like this are the only first step toward creating a clean and sharp API design.

About the author
Vladimir Kaplarevic
Vladimir is a resident Tech Writer at CCBill. He has more than 8 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His engaging writing style provides practical advice and aims to spark curiosity for innovative technologies.
Talk to a Merchant Support Specialist