A REST API is an architectural style for an application programming interface that uses Hypertext Transfer Protocol (HTTP) requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to reading, updating, creating and deleting operations related to resources.
An API is code that enables two software programs to communicate with one another. The API's design spells out the proper way for a developer to write a program, or client, that uses the API to request services from another application, or the server. APIs are a vital mechanism for software interoperability.
REST APIs are also referred to as RESTful web services and RESTful APIs. They're based on REpresentational State Transfer, an architectural style and approach to communications often used in web services development. This approach can also facilitate communication between other application types.
REST technology is generally preferred over similar technologies because it uses less bandwidth, making it more efficient for internet use. REST APIs can also be built with common programming languages such as PHP, JavaScript and Python.
REST browsers are considered the language of the internet. Cloud consumers use APIs to expose and organize access to web services. REST is a logical choice for building APIs to provide users with ways to flexibly connect to, manage and interact with cloud services in distributed environments. Sites such as Amazon, Google, LinkedIn and Twitter use REST APIs.
What are the main elements of a REST API, and how does it work?
A REST API fundamentally relies on the following three major elements:
- Client. The client is the software code or application that requests a resource from a server.
- Server. The server is the software code or application that controls the resource and responds to client requests for the resource.
- Resource. The resource is any data or content -- such as text, video and images -- that the server controls and makes available in response to client requests.
To access a resource, the client sends an HTTP request to the server. Client requests include the following four principal parts:
- HTTP method. This shows what should happen to the specified resource. The four fundamental HTTP methods are known as verbs. POST creates a new resource, GET retrieves an existing resource, PUT updates or changes an existing resource, and DELETE deletes a resource. As the table below shows, these HTTP verbs correspond to the Create, Retrieve, Update and Delete methods or actions, which are referred to as CRUD.
- Endpoint. The endpoint shows where the resource is located and typically includes a Uniform Resource Identifier (URI). If the resource is accessed through the internet, the URI can be a URL that provides a web address for the resource.
- Header. A header includes the details needed to execute the call and handle the response. A request header might include authentication data, an encryption key, more details about the server location or access information and details about the desired data format needed for the response.
- Body. The body contains relevant information to or from the server. For example, a body might contain the new data to be added to the server through a POST or PUT method.
HTTP verb
|
CRUD action
|
POST
|
Create
|
GET
|
Read
|
PUT
|
Update
|
PATCH
|
Update
|
DELETE
|
Delete
|
The server-side hosting the API processes the call and forms a response. When data is requested, the server sends a machine-readable representation of the requested data that the client then processes. Usually, response details include any information needed to interpret the response, such as whether the data is in Extensible Markup Language (XML), JavaScript Object Notation (JSON) or plain text format. The server provides additional data, such as error codes and time stamps, or other instructions for the client.
In short, calls and responses are self-descriptive. This means they will include information on how to process and interpret them.
A REST API breaks down a transaction to create a series of small modules. Each module addresses an underlying part of the transaction. This modularity gives developers flexibility, but it can be challenging to design a REST API from scratch. Several organizations and initiatives provide models for developers to use, including Amazon Simple Storage Service, the Storage Networking Industry Association's Cloud Data Management Interface and the OpenStack Foundation's OpenStack Swift.
A REST API uses commands to obtain resources. The state of a resource at any given timestamp is called a resource representation. A REST API uses existing HTTP methodologies that the RFC 2616 protocol defined, such as GET, PUT, POST and DELETE.
With REST, networked components are a resource to which the user requests access. This is like a black box with unclear implementation details. All calls are stateless; the REST service can't retain anything between executions.
The REST API supports data formats such as application/json, application/xml, application/x-web+xml, application/x-www-form-urlencoded and multipart/form-data.
What are some examples of REST APIs?
Because the calls are stateless, REST is useful in cloud applications. Stateless components can be freely redeployed, resent or retried if something fails, and they provide significant scalability to accommodate workload changes.
This approach works because any request can be directed to any instance of a component. Nothing in the next transaction must be remembered, making using REST APIs preferable for web applications.
The RESTful model is helpful in cloud services because binding to a service through an API is a matter of controlling how the URL is decoded. Cloud computing and microservices are almost certain to make RESTful API design the rule in the future.
REST APIs are frequently used in mobile and web-based applications to access and change data on remote systems across the internet. There are countless examples of use cases, but the following are some of the most popular:
- Mobility. Mobile apps such as Lyft and Uber use REST APIs to access maps and schedule rides.
- Google Maps and other geolocation apps. REST APIs retrieve map data to provide locations, distances and directions.
- Weather. REST APIs are commonly used in weather apps, providing current weather conditions, forecasts and historical data.
- Banking and e-commerce. These apps use REST APIs to access account data and support transactions.
- Streaming services. Spotify, Netflix and other streaming services use REST APIs to access media from remote servers.
- Social media. Services such as X and Facebook use REST APIs to make and manage posts as well as to integrate with other applications.
Principles of the REST API architectural style: What makes a service RESTful?
For a service to be considered a true RESTful web API, it must be designed and implemented according to the following client-server architecture principles:
- The interface must be uniform. This is the most important. All REST APIs must be consistent, providing resource identification in their URIs. They must use standard HTTP methods -- the CRUD operations (GET/POST/PUT, PATCH/DELETE) -- and represent resources in multiple formats, such as XML and JSON.
- Client-server separation. The front end of communication -- the client -- and the back end -- the server -- must be independent of one another; the server must provide the resources, while the client hosts the UI.
- Multiple layers. Though not required, the architecture allows for multiple layers, including proxies, load balancers and authentication; the client doesn't care if it's actually communicating with the web server.
- It must be stateless. Each API call is independent, meaning the server does not track the client's state between requests.
- Caching. Responses use HTTP headers to determine whether they are cacheable; this reduces latency and improves performance.
- Code return. Though not required, the architecture enables the server to return executable code to the client, such as JavaScript, if it is useful.
What are the benefits of REST APIs?
REST APIs have gained enormous popularity due to the numerous benefits they provide developers and organizations, including the following:
- Simplicity. REST APIs use common HTTP methods, including GET, PUT, POST and DELETE requests, making them easy to design, implement and use.
- Independence. Developers enjoy platform independence because they can use almost any programming language to create REST APIs. They work with various client devices, such as traditional web browsers, mobile devices and internet of things devices.
- Flexible. REST APIs support many different data formats, including JSON, XML and plain text. Developers can choose the data format that best suits their client's needs and available server-side data.
- Scalable. The stateless nature of REST APIs supports horizontal scaling, where many API calls run in parallel to handle significant API call loads.
- Cacheable. REST APIs support caching, allowing data to be stored in local memory. This approach can speed server-side response time, potentially improving API performance. It might even eliminate the need for an API call if required data is already on the client from a prior call.
- Secure. REST APIs can secure calls and data exchanges with Open Authorization (OAuth) authentication and Secure Sockets Layer/Transport Layer Security encryption.
- Compatible. Proper use of versioning lets developers treat APIs like any other evolving software, adding new features over time with backward compatibility and supporting legacy features for existing clients.
RESTful API design and architecture constraints and challenges
Dr. Roy T. Fielding, senior principal scientist at Adobe, defined RESTful API design in his 2000 doctoral dissertation as a web service that adheres to the following six REST architectural constraints:
- A uniform interface. Resources should be uniquely identifiable through a single URL. Manipulating a resource should occur only using the network protocol methods DELETE, PUT and GET with HTTP.
- Client-server based. The delineation between the client and server should be clear. The client's domain is the UI and request-gathering concerns, while the server's domain is data access, workload management and security. This loose coupling of the client and server enables each to be developed and enhanced independently of the other.
- Stateless operations. All client-server operations must be stateless. Any state management required should occur on the client, not the server.
- RESTful resource caching. All resources should allow caching unless that isn't possible.
- Layered system. REST enables an architecture composed of multiple layers of servers.
- Code on demand. Usually, a server will send back static representations of resources in the form of XML or JSON. However, when necessary, servers can send executable code to the client.
REST APIs aren't a panacea. Some concepts that might be challenging include the following:
- Endpoint consistency. To be consistent, endpoint paths should follow common web standards, which might be difficult to manage.
- API versioning. Endpoint URLs shouldn't be invalidated when used internally or with other applications.
- Long response times and too much data. The amount of returned resources can grow over time, increasing load and response times.
- Navigation paths and user input locations. Because REST uses URL paths for input parameters, determining URL spaces can be challenging.
- Security. There are many security issues to manage, such as the use of HTTPS, blocking access from unknown IP addresses and domains, validating URLs, blocking unexpectedly large payloads, monitoring and logging requests, and investigating failures.
- Authentication. This requires awareness and use of common authentication methods such as HTTP basic authentication, which allows for a base64-encoded username and password string; API keys; JSON Web Tokens; and other access tokens, such as OAuth 2.0, which is good for access control.
- Requests and data. Some requests might contain more data and metadata than needed, or more requests might be needed to obtain all the data. APIs can be adjusted for this.
- Error codes and messages. A common practice is to use standard HTTP error codes. Error handling might not be able to distinguish whether a response is successful, besides parsing the body or checking for an error.
- API testing. This might be a long process to set up and run, and each part can be challenging. Testing can also occur on the command line with the client URL, or cURL, utility. Testing-related challenges include the initial setup, schema updates, test parameter combinations, sequencing of API calls, validation of test parameters and system integration.
REST API best practices
REST APIs are dedicated software applications designed to support network communication and execution of specific tasks. API development and management are often approached using the same principles and guidelines applied to any other software project. However, the following common REST API best practices can improve API designs and implementations:
- Use nouns in endpoint paths. Where a REST API already employs a verb, such as GET or PUT, in the formation of a request, the resource being accessed should use a noun designation, like GET/datasource or POST/articles. This makes request formation more intuitive for designers.
- Use a well-established data format. JSON is the most common and popular data format for REST API payloads and the default format for popular programming languages such as JavaScript.
- Employ graceful error handling. Be sure to include complete error handling in REST API responses and use standard HTTP response codes to indicate error type. This helps ensure that errors don't crash the client app or server, and they can be understood and corrected quickly.
- Restrict data sets. Use filtering, sorting and other data access techniques to restrict or reduce the volume of data that can be returned to a client. Trying to transfer huge data sets can impair or crash the API. Design the API to request and send only the minimum data requested.
- Maintain security. Design the REST API to use both authentication and encryption as standard practices. Comprehensive security should be applied even to public APIs using freely available data.
- Use caching wherever possible. REST API supports caching on the server and client sides. Using cache on the server side speeds up the server's response time when a frequent request arrives. Using cache on the client side means the data is already on the client and does not need to make the API call. In both cases, API performance improves.
REST vs. SOAP
REST and Simple Object Access Protocol offer different methods to invoke a web service. REST is an architectural style, while SOAP defines a standard communication protocol specification for XML-based message exchange. REST applications can use SOAP.
RESTful web services are stateless. A REST-based implementation is simple compared to SOAP. However, users must understand the context and content being passed along. There's no standard set of rules to describe the REST web services interface. REST services are useful for restricted profile devices, such as mobile devices, and are easy to integrate with existing websites.
SOAP requires less plumbing code -- the low-level, infrastructural code that connects main code modules together -- than REST services design. The Web Services Description Language describes a common set of rules to define the messages, bindings, operations and locations of the service. SOAP web services are useful for asynchronous processing and invocation. The structured formality found in SOAP is often better-suited to complex enterprise-level software integrations and workflows that might overwhelm the design of a similar REST API.
REST and SOAP are both useful and effective methods for building APIs. Choosing between them depends on the API's intended purpose and characteristics.
History of RESTful APIs
Prior to REST, developers used SOAP to integrate APIs. To make a call, developers handwrote an XML document with a Remote Procedure Call in the body. They then specified the endpoint and would POST their SOAP envelope to the endpoint.
In 2000, Dr. Fielding and a group of developers decided to create a standard so that any server could talk to any other server. He defined REST, which has universal rules that make it easier for developers to integrate software.
Salesforce was the first company to sell a RESTful API as part of its internet-as-a-service package in 2000. However, few developers were able to use the complicated XML API. Then eBay built a REST API, which expanded its market to any site that could access its API. This caught the attention of another e-commerce giant, and Amazon announced its API in 2002.
Flickr launched its RESTful API in August 2004, letting bloggers easily embed images on their sites and social media feeds. Facebook and Twitter both released their APIs in 2006, buckling under the pressure of developers who scraped the sites and created Frankenstein APIs. When AWS helped launch the cloud in 2006, developers could access data space in minutes using its REST API. The request for public APIs quickly escalated.
Since then, developers have embraced REST APIs, using them to add functionality to their websites and applications. Today, they are considered the backbone of the internet.
Bad actors can target REST applications. Learn how to protect RESTful APIs from attackers.