Understanding RESTful API
What is an API?
API is the acronym for application programming interface — a software intermediary that allows two applications to talk to each other.
An API is a software which can used by the other software, to communicate with other software or even hardware. It acts as a bridge between different software and devices.
There are so many applications using different technologies and programming languages, which use APIs to interact with each other.
For example, in a Web application there is usually a Front End and a Back End, both of which can be developed using different languages like JavaScript for the frontend or Python for the backend. APIs are developed to help these two communicate and work in conjunction.
Abstraction
Think of an elevator as a software component for a while. Its API would include information about what it can do, like go up, go down, open the doors, etc. It would also include information or an API Documentation about how you could make it do those things.
For instance, if you’re on the ground floor and want to go up to the fourth floor, you would just push the button for the fourth floor.
The API provides a layer of abstraction and doesn’t have to explain what happens in the internals of an elevator. That’s why, if you know how to operate a geared elevator, you can easily operate a hydraulic elevator without having to learn a whole new set of skills, and I’m quite sure you wouldn’t even know the difference between the two.
High Level Programming languages also have APIs which provide abstraction, like Collections in Java and STL in C++, because of which the developer doesn’t need to implement some of the basic components like Lists, Linked Lists, HashMaps etc. from scratch and they are also easy to use and manipulate.
Before we dive into the topic, lets investigate two key terms:
Client — the client is the person or software who uses the API. It can be a developer, for example you, as a developer, can use Twitter API to read and write data from Twitter, create a new tweet and do more actions in a program that you write. Your program will call Twitter’s API. The client can also be a web browser. When you go to Twitter website, your browser is the client who calls Twitter API and uses the returned data to render information on the screen.
Resource — a resource can be any object the API can provide information about. In Instagram’s API, for example, a resource can be a user, a photo, a hashtag. Each resource has a unique identifier. The identifier can be a name or a number.
Privacy & Authentication
Now, there is another security problem. Anyone on the internet with the API endpoint can access your application. This can be problematic if you are sending some data and resources which are private or only authorized personnel can view or use, or if there are some high number of computations taking place in your application to produce the results, you would naturally want to reduce the number of hits on your API, to limit the system usage. This requirement is fulfilled by integrating an authentication mechanism, such as adding a secret key or a token.
What happens in this is, the users of the API need to register themselves on the owner’s platform (generally for a developer account), after which they will be provided with a secret key, which the user would have to send every time they’re making a request at the endpoint. This reduces the number of unauthorized requests and helps the owner of the API to know who all are using their services, and this model can also be used to create paid or subscription-based plans to monetize the APIs. A good example would be Twitter’s API, which has free and premium plans based on how many requests the users can make.
Types of Web APIs
Web APIs are APIs that can be accessed using the HTTP protocol. It can be categorized based on who all can view and use it as follows:
Open/Public APIs: These are available to the developers or the external users with minimal restrictions.
Example is Twitter API.
Internal APIs: These are used within an organization to exchange data and resources and are hidden from any external user. Partner APIs: These are like Public APIs, but these feature restricted access, meant for business partners. These are very common in Software as a service (SaaS) ecosystem.
Example is the Shopify API which enables their partners to access the data present in their partner dashboard, programmatically.
Types of Web API Architectures and Protocols
Different use cases call for different implementations and architectures. This also means different accepted data types and commands. Following are some of the most used architectures and protocols to construct an API:
REST (Representational State Transfer): To be a REST API, an API must adhere to certain architectural constraints, like Client-Server Architecture, Statelessness, Cache ability, Layered System, etc. These are primarily used to access and work with data and require minimum bandwidth. It supports multiple formats such as JSON, XML, HTML, YAML and plain text.
SOAP (simple object access protocol): is a well-established web API protocol, which uses XML as the message format to transfer data. Its main function is to define the structure of the messages and methods of communication. These are driven by functionality rather than data and require more bandwidth than REST architecture. It supports only one message format — XML.
JSON and XML RPC: An RPC is a remote procedural call protocol. They are the simplest and oldest types of APIs. The RPC was developed for the client to execute code on a server. JSON-RPC used JSON to encode its calls, while XML-RPC used XML for the encoding.
REST (Representational State Transfer):
REST, short for REpresentational State Transfer, is a way for servers and clients to communicate. When you use a RESTful API, you’re asking the server for information about something, like a specific user on Instagram or Twitter.
For instance, let’s say a developer wants details about a user from Instagram or Twitter. They’d call the respective API, and the server would send back information about that user, such as their name, number of posts, or followers.
This information usually comes in a specific format, like JSON, which is common for most APIs. It could also be in XML or HTML.
When you ask the server for information using an API, you need to tell it two things:
> What you want: This is the URL (or endpoint) that identifies the specific thing you’re interested in. For example, a user’s profile on Twitter might be identified by their unique username in the URL.
> What you want to do with it: This is the method or action you’re asking the server to perform. The common ones are GET (to retrieve information), POST (to create something new), PUT (to update), and DELETE (to remove).
So, if you want to know details about a particular user on Twitter, you should use a URL (www.twitter.com/udaykishore_resu) that contains the username (udaykishore_resu) and specify the GET method to retrieve the user’s information. This way, the server knows exactly what you’re asking for and can respond with the right information. Twitter uses the username as the identifier, and indeed Twitter usernames are unique — there are no 2 Twitter users with the same username.
For an API to be RESTful, it must adhere to 6 constraints:
1. Uniform Interface: It’s like having a clear set of rules for communication. When you ask for something from the server, you should include what you want. When the server replies, it should give you what you need. For example, if you’re asking for information about a user, the server not only gives you the user’s details but also tells you how you can change them, like updating the user’s name.
2. Client-Server Separation: The client (which could be anything using the API, like a browser or an app) and the server don’t bother each other unless a request is made. The server doesn’t send information unless asked.
3. Stateless: The server doesn’t remember anything about the user. Each request from the user must contain everything needed for the server to understand and respond to it. This way, it doesn’t rely on any past requests.
4. Layered System: There might be multiple servers between you and the main server you’re communicating with. These extra servers might do things like security checks or balancing loads, but they shouldn’t mess with the request or response that you and the main server are exchanging.
5. Cacheable: The server tells you if the data it sends can be saved or if it’s outdated. If it’s cacheable, your system can save it and avoid asking for the same thing repeatedly.
6. Code-On-Demand (Optional): This is like asking the server to give you some code, like a script. For example, when you get a web page in your browser, the page might come with scripts that your browser can run.
We can communicate with servers using the HTTP protocol. With these protocols, we can Create, Read, Update and Delete data — otherwise known as CRUD operations.
But how can we perform these CRUD operations and communicate with data on the server?
We can do this by sending HTTP requests, and that is where REST comes in. REST simplifies the communication process by providing various HTTP methods/operations which we can use to send requests to the server.
The most used methods are:
- GET: The get method is used to Read data on the server.
- POST: The post method is used to Create data.
- PATCH/PUT: The patch method is used to Update data.
- DELETE: The delete method is used to Delete data.
These methods provided by REST allow us perform CRUD operations easily. That is:
Create => POST.
Read => GET.
Update => PATCH/PUT.
Delete => DELETE.
REST API Flow Sequence:
REST uses HTTP protocol as a communication interface. It transfers data through HTTP Methods.
> The user interacts with an application, triggering an HTTP request (GET or POST) to the API.
> The API receives the request, verifies the client, and connects to the database.
> The API executes queries based on the request (retrieve or update data).
> The retrieved or updated data is formatted in JSON or XML.
> The API sends the formatted data back to the client.
> The client application parses the JSON/XML data and displays or use it within the application.
URL (Uniform Resource Locator) & URI (Uniform Resource Identifier):
URL is the address to identify a resource and specify how to access it.
In an API, the URL can be named as Base URL, which means that is the base address used in every request.
Example, http://mysamplecollege.app
URI is used in URL to specify which resource and client would like to access in a request.
Example, http://mysamplecollege.app/emails?department=cse
From the above example, emails?department=cse is the URI.
Here, the client communicates to the server that the request is to retrieve emails with department equals to cse.
Every URL is a URI, but not every URI is also a URL
Parameters & Body Params:
Body Params are only used in requests that must send information such as create or update or delete.
Body of the request which contains all the data that the server needs to successfully process the request.
Example,
{
"project_id":"1",
"sub_project_id":"1",
"jira_snow_id":"567898765",
"task_description":"test",
"hours_spent":45,
"comments":"test"
}
Parameters are of two types they are, Query & Path.
Information that can be sent in a request by the client to get the response from the server.
A variable in URI path that helps in querying / filtering through a list of resources.
Example of Query Parameter, http://mysamplecollege.app/emailsdepartment=cse
A variable in URI path that helps in pointing towards specific resource.
Example of Path Parameter, http://mysamplecollege.app/departments/cse
From above examples,
Base URL: http://mysamplecollege.app
Query parameter: emails?department=cse
Path Parameter: departments/cse
Request Headers
Request Headers used to send extra data, specifying proper format and data to retrieve.
Authorization: Bearer token
Accept: Application/json
HTTP Status/Response Codes
With every request made to the server, we get http status / response codes in return.
1XX : Information
2XX : Success
3XX : Redirection
4XX : Client Error
5XX : Server Error
Why REST APIs?
Rest APIs come with several advantages that make them popular:
> Simplicity: They’re easy to understand and use. Their structure mirrors how the internet works, using standard HTTP methods like GET (to fetch data), POST (to send data), PUT/PATCH (to update data), and DELETE (to remove data).
> Scalability: Rest APIs can handle many users and requests because they’re stateless. Each request contains all the info needed, making it easier to scale up by adding more servers.
> Flexibility: They support various formats like JSON, XML, or HTML, giving developers the freedom to choose the format that suits their needs.
> Platform Independence: Rest APIs work on any platform or device that can connect to the internet, making them highly compatible.
> Ease of Integration: They allow different systems and services to communicate and work together seamlessly. This makes it easier to combine various services to build complex applications.
> Enhanced Performance: Rest APIs are lightweight and don’t carry the extra overhead of other protocols. This leads to faster communication between client and server.
> Better Developer Experience: Their simplicity and standardization reduce the learning curve for developers, enabling faster development and easier debugging.