top of page

Building RESTful APIs using Flask in Python

What is REST?


REST is acronym for REpresentational State Transfer.

It is an architectural style often used in the development of Web services, as an approach to communications. REST Web services are a way of providing interoperability between computer systems on the Internet. REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations.

If that went right over your head, let’s understand REST with a relevant example -

Consider booking tickets for a movie on the BookMyShow app. You’d have to provide several details, and in return, you get a personalized search result - a list of movies. Now this response data is not static information - it changes from time to time - depending on what day it is, or availability of seats, which city you’re booking in, etc.

Consider trying to check a Weather Updates app, to note the temperature in your city. The temperature values displayed change during the course of the day, and from one city to another, etc. Again, this data is not static.

In both these examples, dynamic data served on the app is received by the Web server.

The client requests the server for the desired information - via an API - and the server then sends a response to the client.

The response is sent to the browser in the form of an HTML Web Page.

But you already have an app with a very precise design, waiting to display the results of your search in a formatted manner. The app wouldn’t want an HTML Page, rather just the data. A structured format would be a more relevant response - here is where formats like JSON and XML come in. The servlet response is in either of these formats. Both JSON and XML have a proper hierarchical structure of data.

Now the catch to this entire request - response framework is that obtaining the required information involves numerous methods. When trying to retrieve complex data, it becomes extremely cumbersome.


Enter REST.


The Rest API creates an object for the requested data, and sends the response to the client as values of the object.

So now we have an object of the data, and we are sending the “state” of the object as the response to the client. This might hint why this architectural style is called Representational State Transfer - It entails the transfer of the “representational” state of the object.

Now that we have tried to decode the term REST, we can revisit our understanding.

Normally, we would think of the entire process as a series of HTTP requests sent to the server, where some computation occurs, and then the client receives HTTP responses.

With the incorporation of REST, we can think of the process as querying the Web for some data using an object, and receiving the state of the object in the form of data - current values - of the object, as response.

The architectural style of REST helps in leveraging lesser use of bandwidth to make an application more suitable for the Internet. It is often regarded as the “language of the Internet” and is completely based on the resources.

The REST API breaks down a transaction in order to create small modules. Now, each of these modules is used to address a specific part of the transaction. This approach provides more flexibility but also requires a lot of effort to be built from scratch.

REST makes it easy to generate the state of the object for a response, by trying to map it its methods to HTTP methods.


Methods of a REST API


Working with the Web involves four basic operations on resources, described by the acronym CRUD - Create, Read, Update, Delete. These four methods are implemented using HTTP methods as REST API Methods :

C - Create the resource - POST

R - Read the resource - GET

U - Update the resource - PUT

D - Delete the resource - DELETE

You might notice how all these methods are based on resources.


Resources


The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service, a collection of other resources, a non-virtual object (e.g. a person), and so on. REST uses a resource identifier to identify the particular resource involved in an interaction between components.

The state of the resource at any particular timestamp is known as resource representation. A representation consists of data, metadata describing the data and hypermedia links which can help the clients in transition to the next desired state.

Hence the REST API methods are Resource Methods, but they are not HTTP methods. They only map to HTTP Methods thereby correlating REST and HTTP.


Guiding constraints of a REST API


Like any other architectural style, REST also has its own guiding constraints to be satisfied if an interface is to be referred to as RESTful:

Client-Server: This constraint operates on the concept that the client and the server should be separate from each other and allowed to evolve individually.

Stateless: REST APIs are stateless, meaning that calls can be made independently of one another, and each call contains all of the data necessary to complete itself successfully.

Cache: Because a stateless API can increase request overhead by handling large loads of incoming and outbound calls, a REST API should be designed to encourage the storage of cacheable data.

Uniform Interface: The key to the decoupling client from server is having a uniform interface that allows independent evolution of the application without having the application’s services, or models and actions, tightly coupled to the API layer itself.

Layered System: REST APIs have different layers of their architecture working together to build a hierarchy that helps create a more scalable and modular application.

Code on Demand: Code on Demand allows for code or applets to be transmitted via the API for use within the application.

REST provides a much more concise yet modular approach to querying the Web, but like every advancement in technology, it comes with its own drawbacks.

Programming languages are not resource oriented, and like we saw with the REST API Methods, REST is entirely based on resources. This causes the handling code that maps URIs to be quite complicated. While this might be a REST - inherent disadvantage, several others are drawbacks of REST over HTTP Implementation.


Web Frameworks


Now that we’ve tried to understand a suitable architecture to build APIs, let’s talk about Web Frameworks to deploy RESTful APIs -

A Web application framework is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs. Web frameworks provide a standard way to build and deploy web applications on the World Wide Web.

Flask is a micro web framework written in Python - it provides functionality for building web applications, including managing HTTP requests and rendering templates. Since it is a micro framework, it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

So to connect REST and Flask - an API is built in Flask, adhering to the REST architecture, making it a RESTful API.


Why Flask?


Python has a number of web frameworks that can be used to create web apps and APIs. The most well-known is Django, a framework that has a set project structure and includes many built-in tools. This can save time and effort for experienced programmers, but can be overwhelming. Flask applications tend to be written on a blank canvas, so to speak, and so are more suited to a contained application.

Flask maps HTTP requests to Python functions. When we connect to the Flask server, Flask checks if there is a match between the path provided and a defined function. It runs the code in the function and displays the returned result in the browser. The process of mapping URLs to functions is called routing.

Now a RESTful API can be created on Flask in two ways - either without any external libraries, or using the flask_restful library.

Flask Restful is an extension for Flask that adds support for building REST APIs in Python using Flask as the back-end.

The main building block in flask_restful is a resource. Each resource can have several methods associated with it such as GET, POST, PUT, DELETE, etc. for example, there could be a resource that performs a mathematical calculation whenever a get request is sent to it, with the input values and the operation symbol. Each resource is a class that inherits from the Resource class of flask_restful. Once the resource is created and defined, we can add our custom resource to the api and specify a URL path for that corresponding resource.

Here’s a simple program to help understand how we can use the flask_restful library to run a code to compute the square of a number:


📷


Output:


📷


While REST has its ups, other approaches to API development may be more relevant for some kinds of applications - GraphQL, gRPC, etc.

REST focuses mostly on transfer of representation state, whereas GraphQL emphasizes on data retrieval. The difference is how data/referential integrity is enforced.

For example, REST principles typically make people think in terms of entities. Take a car for instance, which has properties like “wheels”, “doors”, “color”, etc. Each “car” has the same properties, which can be changed. The state of a car can also change. It could be “parked”, “accelerated”, “stopped”, etc. Enforcing state/properties of an entire entity is well suited for REST. GraphQL would ask questions like “Give me the color of all cars without wheels”. It retrieves data, but doesn’t necessarily imply structure. This is a powerful functionality that scopes higher than the idea of objects.


Tech always has new approaches, but if you keep an eye on the industry long enough, you’ll eventually see it circle back to the same common principles. So, will a new tech replace REST? Probably not. It might fall out of favor in some situations, but it may gain favor in others.

19 views0 comments

Recent Posts

See All

Comments


bottom of page