How Does a REST API Work with Examples and Challenges

How Does a REST API Work with Examples and Challenges

API is the abbreviation for?Application Programming Interface?and is a piece of code that specifies how different software components should interact and communicate programmatically. Many are not aware that, under most modern user interfaces, dozens of requests are being sent to API servers for data. The client then processes data returned by the API server to elicit some outcome in the user interface.

For example, if you have ever searched on an aggregator website for the best deals on flights or hotel bookings, a “request” for data based on your search criteria was made (after clicking the submit button) to an API specializing in flights or bookings. After the aggregator website retrieves the data using the API, the search results are displayed to you.

The aggregator website and its associated databases did not store the data appearing in the search results. Instead, the website sent a request for data matching your search criteria to an external web service (i.e. API). The API returned the requested data to the website, and the website parsed the data and rendered the search results.

What is a REST API?

There are many kinds of APIs. Sufficiently describing all of them here would require many blog posts. For our purposes going forward, we will limit the scope of discussing APIs just to REST APIs.

REST stands for?representational state transfer?and is a particular kind of architectural style that APIs considered “RESTful” are constrained by and “conform to”.

REST APIs are a very common and important type of API that uses HTTP protocol for data transmission. Since this HTTP protocol is used, a REST API is considered a “web service” that deals with the interaction between client applications and API servers. Using this protocol, a client sends an HTTP request for data to an API Server and then the server sends an HTTP response with encoded data back to the client.

The HTTP protocol used by REST APIs allows for platforms and systems written in different programming languages to interact with one another. For example, a client application written in C# can interact with an API server written in Java. This interoperability between systems makes web services very popular in modern software development, and REST APIs in particular.

REST API Use Cases

REST’s separation of concerns for the client and server makes it attractive for many kinds of projects, whether mobile development, web development, etc.

Here are common use cases:

  • Cloud applications?– REST’s advantage of statelessness (discussed more later) is suited well to cloud applications.
  • Cloud Computing?– REST supports cloud computing in controlling how URLs are decoded during client-server communication.
  • Microservices?– REST APIs connect microservices together into one application.

Anatomy of REST API request

The APIs set the rules for how client applications/backends and API servers can communicate programmatically. The API determines how the client needs to send requests, and what sort of information is returned by the API to the client.

The basic components of REST API requests are discussed below.

Resources

The different kinds of information the client can request from the API are called “resources”. Think of a resource as a type of data object returned by the API.

For example, the well-known Swagger Petstore API consists of several resources, namely: Pet, Store, and User.

No alt text provided for this image

All relate to the central theme of the pet store, but each represents the different data objects you can create, manipulate, or delete.

You will notice when reading?API documentation ?that endpoints are grouped under their related resource. For example, the “pet” resource has several related endpoints (discussed soon) to take action on a pet resource. You can create, update, or delete Pets.

To solidify the concept of resources: When you create a Pet, know that the API returns a Pet resource or pet “object” that in some sense represents a physical pet added to the pet store’s system.

Endpoints

If you were to expand either the?pet?or?store?resource, you would see various endpoints. Each endpoint does something different.

Endpoints are at the core of API requests and usually stand out in API documentation. Most notably, the?method?(or action, like POST) of the request and the?end path?(ex. /pet) of the endpoint are highlighted. The following is a list of endpoints of the?pet?resource.

No alt text provided for this image

When you send a request to an API, you send an HTTP request using the specific “end path” of the endpoint. The end path comes after the API’s base URL. For example, the base path of the Swagger Petstore is https://petstore.swagger.io/v2/, whereas an end path for a pet store endpoint looks like /pet. The full Resource URL used to send a request is https://petstore.swagger.io/v2/pet.

An endpoint can have multiple paths and methods (discussed soon) that elicit different responses from a resource. The request below sends a request using the /pet endpoint with the POST method. POST indicates you wish to create something, in this case, a pet.

No alt text provided for this image

The request below sends a request using the same?/pet?endpoint, except this time you use the?GET?method to retrieve details of a pet rather than create one. Notice that you need to append the?petId?of the pet to your request (parameters discussed later).

No alt text provided for this image

Methods

As briefly discussed, HTTP methods are sent with API requests to indicate the actions you would like to take toward a resource. There are many API methods, so I will only list some important ones:

  • POST request?– creates a resource.
  • GET request?– retrieves information about a resource.
  • PUT request?– updates or creates a resource.
  • DELETE request?– deletes a resource.

HTTP methods correspond to CRUD Operations. For example, the HTTP methods POST, GET, PUT, and DELETE correspond to create, read, update, and delete CRUD operations.

Parameters

Think of parameters as options or filters passed with an endpoint that affect what information is returned in the response. There are different types of parameters, such as:

  • Header Parameters?– Included in the Request Header of an API request and are usually related to authorization. For example, many times an access token parameter is included in the Request Header that authorizes requests of the client to the API.
  • Path parameters?– Included in the Resource URL of an API request and are indicated by curly braces at the end of an endpoint’s end path. For example GET /pet/{petId}.
  • Query string parameters?– Included in the Resource URL of an API request and appear after a quotation mark (?).

Note that endpoints may or may not use all of these kinds of parameters. However, header parameters are usually included for authorizing requests.

Request Body

Request bodies are essentially JSON objects passed in the body of an API request and are often used with POST or PUT methods. Even though they are not classified as such, they are like parameters that take the form of a JSON object rather than a key-value pair like a normal parameter.

REST’s Core Principles

REST’s core principles are what makes it so attractive in software development.

Client and Server

REST APIs have an architecture designed to separate the client from the server so both can evolve independently. The client is not concerned server’s data storage, and the server is not concerned with the user interface. This separation of concerns makes user interfaces very portable and server elements more scalable.

Statelessness

The statelessness restriction of REST ensures state data is only stored in the client application and not on the server. Every request made by the client is independent of any previous requests and includes all required information. Since the server stores no session-related information, the client application manages its session data.

Cacheable

When a client sends a request to a REST API, the API must indicate that the response either can or cannot be cached. Also, it must indicate how long the client can cache responses. Caching can improve availability and performance by reducing the number of API requests since the client can leverage cached data for a certain duration of time.

Uniform Interface

RESTful APIs are constrained in ways that make a uniform interface for clients. For example, RESTful APIs must:

  • Identify their resources.
  • Use HTTP protocol to describe their operations (i.e. POST, GET, PUT, DEL).
  • Use self-descriptive messages that allow for interpretation by the client without application-specific knowledge.
  • Require client applications to use hyperlinks to drive interactions with the API’s resources.

Layered System

REST allows for a layered system architecture where each layer plays a certain role in the system and only interacts with other designated layer(s). For example, you can have an API server, a data storage server, and a server for authenticating client requests using a layered architecture.

There can also be intermediary servers between the client and server that deal with security, load balancers, and proxies that can improve system availability.

Benefits of REST

Scalability

The separation of the client from the server components increases the portability and simplification of server components. REST’s multi-layered architecture also restricts the interaction of layers. These factors contribute to REST’s scalability.

Portability / Independence

Since the user interface is separated from the server, it can be ported to many different platforms. REST APIs themselves are also adaptable across platforms which allows for easy testing during development.

Flexibility

The client-server separation also makes it easy to migrate data between servers and roll out new changes quickly.

Uses Less Bandwidth

RESTful APIs are advantageous over SOAP APIs in terms of bandwidth. REST APIs send and receive JSON payloads commonly, as opposed to SOAP which uses XML. XML payloads are larger than JSON, thereby making SOAP APIs require more bandwidth than REST APIs.

Easy Integration

REST APIs are generally easier for developers to integrate into their applications because they can focus more on the user interface, functionality, and business rules rather than server components and data management handled by the API Server.

REST Challenges

While the pros of using REST for many outweigh the cons, development teams should still be aware of the potential issues of this architectural style.

Endpoint Reliability

While it is best practice for API endpoint URLs to be consistent as an API evolves, URL uniformity may become an issue for larger systems as the number of possible endpoint paths and methods increases.

API Version Control

As new versions of APIs are released, version control inevitably becomes an issue development teams struggle to manage. To protect compatibility, older endpoints require support to remain valid until they are phased out. This comes at a cost of time and resources.

Increasing Response Times

An example of two factors that can cause slowness in response time is the size of a server and the number of servers involved in the processing of an API call and retrieving data. With larger databases comes more data that has to be sorted and processed, especially if there are numerous databases.

Large Data Responses

Sometimes it is unavoidable when a server’s response to an API request unnecessarily provides all possible data when only a subset is needed. The client application has to be robust enough to parse the information and extract what it needs. A GET request is a common occurrence that can trigger the retrieval of a lot of data.

Security

While the layered architecture of REST has security benefits, that does not mean applications do not have to be encrypted. Without encryption, applications may expose sensitive data.

Also Read:??Agile Documentation: Methodology & Best Practices

Top REST API Examples

Plaid

No alt text provided for this image

Source

The marketplace for SaaS (Software as a Service) products is sparking major growth for REST APIs in the FinTech arena. One of the top companies is Plaid, which is among a select number of companies promoting the “democratization of data” in financial services.

The “democratization” is about making data available for all parties (developers, business stakeholders, consumers), regardless of their technical competencies. This model allows you to leverage the raw potential of data to create experiences that fit the end user’s needs.

Plaid takes a highly “use case” focused approach to how it markets the potential of its services. Plaid’s clear communication and guidance for how to leverage its services is a differentiator.

For example, there are a whole host of use cases for why someone would use Plaid’s services, whether it be for applications in personal finance, consumer payments, lending, banking, or wealth management. Each use case is explained in detail in its documentation. Plaid also has connections to thousands of financial institutions that developers can leverage in their apps.

Twitter

No alt text provided for this image


Source

As far as social media goes, Twitter’s reach is enormous, with an average of 206 million active users. Developers should be aware of the benefits of the Twitter API for integrating Twitter’s functionalities while simultaneously promoting their applications through the platform.

For example, developers can leverage Twitter’s identification process to reduce or eliminate the process of registration. The API allows you to display tweets to your users based on certain criteria like location or trending hashtags. Twitter’s reach also allows you to market your application effectively using their data.

While other APIs from notable social media companies are available, it is the capabilities and reach of the Twitter API that make it stand out.

AWS AI Services

No alt text provided for this image

Source

REST APIs for artificial intelligence, data science, and machine learning applications are growing steadily. Among the top-tier companies offering these services is AWS AI Services (i.e. Amazon) which allows developers to incorporate AI functionality into their applications to make for a more adaptive and intelligent interaction. AI can also help secure data exchange between systems by detecting potential security vulnerabilities.

While there are many AI APIs available, Amazon’s services offer the widest range of functionalities among their kind and have the added benefit of easy integration on their side.

Summary

APIs have become the glue that ties together separate systems, allowing them to exchange data using a common architectural model (notably REST) which increases scalability, flexibility, and independence as clients and servers evolve independently of one another.

Both new startups and entrenched tech companies are expanding their existing offerings and rolling out new SaaS products as the “democratization of data” becomes important for businesses that want to stay on the cutting edge.

The conversation about the value of APIs is no longer exclusively in the realm of “coders”. Stakeholders from all areas of business stand to benefit from understanding APIs and how they can be used to solve business challenges.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了