An Introduction To REST API & REST Programming
Once you’ve developed an app or a website that provides a service to your customers, the next step is to implement an API. This will allow your app to communicate with other programs. For example, let’s say you run a website for a specific venue that sells tickets to events. By implementing an API, other websites can access the data they need to provide their visitors with information about your ticketing prices and events as well. It’s how websites like Ticketmaster and SeatGeek are able to function. When it comes to APIs, you’ll want to strongly consider implementing a REST API.
REST APIs are one of the most popular types of APIs because they were designed to take advantage of almost any existing protocol; however, when used for web APIs, they usually take advantage of HTTP. We have compiled an in-depth overview of what REST APIs are, what RESTful APIs are, how they work, and what you need to know about them.
REST API: An Overview
A REST API is a type of API (application program interface) used to design networked applications. It’s the most efficient, logical, and widespread standard when it comes to the development of APIs for online use.
What Is REST?
REST (representational state transfer) was defined by Roy Fielding, who is considered one of the leading authorities on Network Architecture (not to mention the father of HTTP specification) as a core set of principles, properties, and constraints. It’s any interface between systems that uses the HTTP protocol to obtain data and generate operations in all possible formats, including JSON and XML. Basically, REST is a way for components on the web to communicate using the HTTP protocol. REST has become a more popular alternative to other data exchange protocols, including SOAP, which is much more complex.
What Is an API?
An API (application programming interface) is a set of functions, communication protocols, procedures, and tools used to build software. In simpler terms, the API is the messenger that takes your request, relays that request to a system, and then returns the system’s response back to you. Think of the user as a person eating at a restaurant. The kitchen is the system that executes the order. The API is the waiter that tells the kitchen (system) what you’re ordering and then delivers the meal (response).
Who Can Use REST API?
Anyone can use REST APIs as long as they are providing some kind of service through their app or site. Many businesses even use REST APIs for their WordPress sites. This is because developing a REST API for the web is relatively easy since you won’t have to install additional software or libraries. It’s why REST APIs are developed by both small and large companies alike.
REST API Users
The following are just a few examples of companies that use REST APIs:
- Twitter – Twitter has a wealth of information that is of incredible value to companies around the world. As a result, they built a Twitter API platform that provides broad access to public Twitter data, such as accounts and users, tweets and replies, and ads. Even direct messages are accessible as long as users explicitly granted permission to a specific application.
- Facebook – Facebook offers a variety of Facebook APIs, including Facebook Marketing, Facebook Ads, Facebook Atlas, and Facebook Graph. Their APIscan provide you with access to profiles, groups, photos, and event data, thereby adding social context to your apps.
- Dropbox – The Dropbox API allows users access to files that have been stored and synced online and across all computers.
- Google Translate – Google provides a Google Translate API that can be used by your apps or website to instantly translate text into over a hundred languages.
Fundamental Properties Of REST
The following fundamental properties of REST have many advantages compared to other types of APIs (such as SOAP):
- Performance – This refers to the performance in component interactions. These can have a big effect on the network’s efficiency as well as the user-perceived performance.
- Scalability – REST architecture is stateless, which means that client sessions are stored on the client and not on the server. It’s why it’s called Representational State Transfer. This allows a REST API to scale to millions of users simultaneously.
- Simplicity – REST APIs can be very simple to build and scale even if you’re working with limited resources. This is due to its uniform interface and HTTP protocols as well as the fact that you don’t need to install additional software or libraries.
- Modifiability – Using REST allows the developer to make changes in the app’s components according to developing needs. These changes can be made even while the app is running.
- Visibility – Using REST, all communication between servers and components will be visible.
- Portability – Program code can be moved along with the data because all of the components are portable.
- Reliability – REST is a very reliable architecture because the system will never fail, even if failures occur within connectors, components, or data.
Architectural Elements Of REST
One of the reasons that REST is so popular and easy to use is because its architecture is the basis of the web itself. This means that any developer that has a knowledge of web architecture will be familiar with how REST works. Keeping that in mind, the following are the two main elements of REST:
Resources
Resources refer to the information a client can request that’s stored on a server. Every resource is identifiable by a unique URI (Uniform Resource Identifier).
Representations
The representation refers to how the resource is represented. For example, the resource may be provided to the client as simple text, XML, or HTML. Clients can request specific representations by providing metadata as part of their request.
What Is RESTful API?
The term RESTful API can be a little confusing. This is because there’s really no difference between a REST API and a RESTful API. Basically, REST is a type of software architecture that uses the existing protocols of the web. A RESTful API is a web service that implements REST, meaning that it conforms to the constraints of REST.
Limitations of RESTful API
There are six main constraints of REST that an interface will need to satisfy in order to be considered a RESTful API, which are these:
Client-Server
The client-server constraint refers to the need for the client (the front-end of the app) and the server (the back-end of the app) to evolve separately without depending on one another. The resource URIs should be the only thing a client should know. It’s worth noting that this is not a difficult constraint to meet since client-server constraints are are common practice in web development these days.
Stateless
Stateful apps use the data saved from each client session for the next time that the user makes a request. To be stateless, the app cannot save any client data that’s generated in one session on its server to be used in the next session. Essentially, the app must treat every single request as new, whether or not the client making the request has made previous requests during previous sessions. If your app requires the user to log in and perform authorized operations afterwards, then each client request needs to contain all the necessary information to service that request, such as authentication and authorization details.
Cacheable
Data and responses need to be cached to improve the performance of the app on the client’s side. It also improves the scalability of the server since caching reduces the load. Caching can be done on either the server side or the client side.
Uniform Interface
The interface of your API needs to be uniform, meaning that once a developer gains an understanding of your API, they should be able to approach other APIs in a similar manner. To create a uniform interface, first decide the interface for resources inside the system. Resources should only have one logical URL to collect additional data or data that is related. Keep in mind that a single resource should contain each and every item in its representation and shouldn’t be too big.
Layered System
A layered software architecture is made up of a number of layers that correlate to different services. A layered system makes it easier to make changes to individual layers, allowing you to manage and maintain the app in a more agile and flexible manner. Layered systems are generally divided into three main layers: the presentation layer, the application layer, and the data layer. Additional layers can be built on top of these three foundational layers.
Code On Demand
Although you’ll generally be sending static representations of resources in the form of JSON or XML, code on demand is permitted. This means that you can provide clients with executable code to support a specific part of your app. For example, if a client requests a UI widget rendering code from your API, you can provide it. This constraint is optional.
How REST API Is Programmed
Now that you have a better understanding of what REST APIs actually are, let’s look into how they are programmed. There are four steps to creating a URL (Uniform Resource Locator), which is called the request. Once you submit the request, you’ll be sent the data you requested, known as the response.
The Makings Of A Request
There are four major components of a request:
- The Endpoint – The endpoint is the URL that you are requesting. It’s structure includes the root-endpoint, the path (which determines the resource you’re requesting for), and the query parameters.
- The Method – The method refers to what action you want to take, whether it’s just looking at the resource, updating the resource, replacing the resource, or deleting the resource.
- The Headers – The headers can be used for several purposes, including providing a summary about the body content or providing authentication. Headers provide information to both the server and the client.
- The Data – The data refers to the information you want to send to the server. It’s only used if you’re altering or deleting the resource.
1. The Endpoint
The first part of the endpoint requires you to input the starting point of the API that you’re requesting from, also known as the root-endpoint. For example, if creating a root-endpoint, it would look something like this: https://api.endpoint.com.
What Is Path
The path is the resource you’re requesting. Think of it as a category. You’ll have to look at an API’s documentation to determine what paths are available. However, when creating the URL, it would look like this: https://api.endpoint.com/tag/path/ .
Test Your Endpoint With cURL
You can use any programming language to send a request; however, cURL is the recommended command line utility since most API documentations are written with reference to cURL. This means that if you are familiar with cURL, you shouldn’t have any issues understanding API documentations. You’ll need to install cURL if you don’t have it. To use it, type in “curl” followed by your endpoint; for example: curl https://api.endpoint.com. The server should send you a response once you’ve submitted it.
JavaScript Object Notation Or JSON
JSON is an open-standard file format commonly used to send and request data through a REST API. Representations are often sent back in JSON. Properties and values will be represented within double quotation marks, such as: “property” and “value”.
2. The Method
There are several actions that you can take when submitting a request. These actions are defined as “methods.” These methods are represented by HTTP verbs. The uniform interface of REST requires the use of HTTP verbs as opposed to noun-based resources.
Types Of Method
The following are the most commonly used methods (or HTTP verbs) for RESTful services:
Get
“GET” means to retrieve or read resources. You cannot change a resource in any way using the GET method.
Post
“POST” means to create resources. POST requests are made to add new resources into the database. Note that submitting two identical POST requests will result in two different resources with different resource IDs that will include the same information.
Put
“PUT” means to update or replace resources. If the resource that you request doesn’t exist, a new resource may or may not be created depending on the API.
Patch
“PATCH” means to partially update or modify resources. It’s different from the PUT request in that a PATCH request partially updates an existing resource, while a PUT request will replace the resource altogether.
Delete
“DELETE” means to remove resources. A DELETE request will permanently remove a resource, which means if you submit the same DELETE request a second time, it will return a 404(Not Found) response.
3. The Headers
The use of headers allows additional information to be provided by either the client or the server with either the request or response. The following are the different types of headers:
- General – General headers apply to both requests and responses; however, they do not have any relation to the data that’s relayed in the body.
- Request – A request header provides more information about the resource that the client is requesting or about the client itself.
- Response – A response header provides more information about the response, such as the name or version of the server itself.
- Entity – An entity header provides additional information about the body content, such as the type of content in the body or how long it is.
A header telling the server what kind of content type to expect might look like this: “Content-Type: application/json”. Using cURL, you can simply send HTTP headers through the –header or -H options.
4. The Data
The data option can only be used with POST, PATCH, PUT, or DELETE requests and not the GET request. This is because the data refers to the information you’re sending to the server. Using cURL, you’ll use the -d or –data options.
Authentication
The last thing you’ll want is for someone to impersonate you in order to perform actions through your REST API. This could result in valuable information being stolen or deleted. To prevent your database from being altered by an unauthorized person, put up an authentication wall.
Authenticating Yourself
To set up an authentication wall, you have two option. These include the following:
Basic Authentication
Basic authentication refers to a very simple form of authentication using a username and password. To execute requests, you would have to provide both.
Using A Secret Token
The second form of authentication is through the use of a secret token. This allows you to authenticate yourself using a social media network, such as Facebook, Google+, or Twitter.
Encountering HTTP Status Codes
Once you’ve submitted a request, you’ll receive an HTTP status code immediately. This lets you know if your request was successful or if it encountered an issue. The following are the HTTP status codes that you may receive:
- 200+ – A 200+ status code means that the client’s request went through successfully.
- 300+ – A 300+ status code means that the client’s request was redirected to a different URL.
- 400+ – A 400+ status code means that there was an error with the client’s request on their end. This usually means the data is wrong or missing.
- 500+ – A 500+ status code means there was an error with the client’s request, but that it was an error on the server’s end.
Updating API Versions
APIs are generally updated once in a while. Sometimes, the developer may completely upgrade to another version. If the code was written for an older API but the request points to an upgraded API, it can cause the app to break. The solution is to request for a specific API version. This can be done in two ways based on how the API was written.
1. Directly In The Endpoint
The first solution is to name the version in the endpoint. Let’s say the new version of the API is version 1.1, then your request would look something like this: https://api.endpoint.com/1.1/account/settings.json .
2. In A Request Header
The other solution is to define the version in the header. Such a header would look like this: Accept-version: v1 .
Tips For Better Results
The following tips will help to improve your REST API results:
- Use HTTPS verbs – HTTP verbs make it much easier to identify what any given request does.
- Use practical resource names – Make the resource names practical to improve what a given request does. While URL query-string parameters can be effective as far as filtering goes, they’re not effective as resource names. By using practical resource names, your API will be easier to use. Make sure that your resource names are nouns as well.
- Use HTTP response codes – Response codes will help the client understand the status of their request and can make it easier to figure out how to correct their request if something is wrong.
- Offer both JSON and XML support – JSON is usually considered the standard, which means that you should offer JSON support at the very minimum. If you can, offer XML support as well; however, this can sometimes be too expensive to be worth doing.
- Start small and create larger resources later – When you first implement REST API, it will be easier to just imitate the database architecture of your system or the underlying application. Then you can just create larger resources from individual resources later on. This will be a lot easier than trying to create individual resources from larger aggregates from the start. Begin with smaller, more easily defined resources and then create more resources that are use-case-oriented later.
- Return links in responses – APIs become more helpful when links are returned in the responses. Links are beneficial because they show clients how the data they received was obtained. You can add a link on resource creation through POST by using the location header.
Finalizing Your REST API
If you have built an app or website, consider implementing a REST API. RESTful APIs are both scalable and flexible, high-performing, efficient, and take up minimal resources. And REST uses the HTTP protocol, which means it’s easy to use and maintain.
Need more information? Contact us today! Our trusted advisors would be glad to help.