top
Kickstart the New Year with exciting deals on all courses Use Coupon NY15 Click to Copy

Create an API Using Flask in Python

In this article, we are going to learn how to create an API using Flask in Python. Before getting into coding the API, I would like to give a brief introduction of the Flask framework for Web services and what an API is. Flask It is a microframework for Python based on Werkzeug and Jinja2. Basically, it's a lightweight framework for creating web services using Python. Whereas Django is heavy compared to Flask. Flask is super easy to setup and gets things ready. API (Application Programming Integration) API is a code that allows two software programs to communicate with each other. API defines the correct way for a developer to write software that requests for services from other applications. APIs are generally implemented using function calls. API needs to be documented after coding so that developers can read and understand what kind of operation they would do on each function call. We are going to implement RESTful API using Flask as an example. REST architecture was designed to fit HTTP protocols. Resources are represented by URIs and each resource may be changed or queried on client’s request. ​Source: miguelgrinberg.com Implementation So we have a basic idea of what Flask and API are. We would follow a project-based approach to create an API using the Flask Framework. We would create an API that would give all the image links from the Zeolearn magazine section. You guessed right. We would need to write a bit of scraping code but for this exercise it's minimal. Instead of giving links you can return any other resource as a response to request.  Above code snippet implements a simple API endpoint at index URI i.e if this web service is hosted at http://example.com and we call the endpoint ‘/’ which is preceded by hosting URL, which finally looks like  http://example.com/  then we would get output as shown in the image below index() function is routed to ‘/’ using app.route(<URI>, <HTTP method>) URI is relative to base URL. Routing is done by using app.route decorator and the decorator simply maps URL to a resource. jsonify() turns json output into a Response object with the application/json mimetype. We can check HTTP verbs of the incoming request in the following way We can create Response objects for various mime types in the following way Output: Now we will implement more complex resource URIs. Let's create an endpoint that takes an integer number from request and returns that many number of image urls as a response to the request. As I told you above, we are going to write a little bit of scraping code to extract image URLs from Zeolearn magazines section. First route function to desired URI, for example, I am routing to ‘/magazine/photos/<number_of_images>’, observe how I put number_of_images inside angular brackets and that's because it a variable, everything variable needs to be put inside angular brackets as they would be changing with different client’s request. Scraping code used is really simple to understand in this example. I just requested the magazine section of zeolearn and extracted all the image links from img tags in the html page. I used BeautifulSoup module for web scraping. Let's not dive too deep into scraping, the only thing to understand is that you obtained the required data that you want to send as response. Now jsonify the data and send. Response of above endpoint is shown in image below - We have seen GET requests in the above examples, now let’s see how do we handle POST requests. But before that let’s see how Wikipedia defines these methods- GET - Requests a representation of a specified resource. POST - Submits data be processed (e.g. from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updation of existing resource or both. In the example below, we created a POST method that checks the type of data received whether it is of json type or plain text and returns the data after appending its type. Generally, the database is updated or a new entry is created in the database with the information received in the POST request. All the arguments used in the curl tool can be referred here. In general, for the implementations of API, the web service has access to database and queries database based on client’s request. This is, in fact, one of the reasons why REST architecture is preferred. Suppose you want to make Application which stores users data somewhere and the application has different clients like Android, web app, iOS app, etc. So instead of creating a separate backend for each client, we prefer to create an API which serves the data to all the clients. API does this by exposing some endpoints like we created in the example above. We created two end points- one at ‘/’ and other at ‘/magazines/photos/<number of images>’. Clients can make a request to any endpoint to get the response. Similarly, we can make other endpoints of the API and document them for developers to use it in client-side applications.   Now you would be understanding why documentation of API is necessary. So that the other developers can look at the documentation and understand what type of data each API endpoint requires and what type of data it returns in response to client’s request.
Rated 4.0/5 based on 0 customer reviews
Normal Mode Dark Mode

Create an API Using Flask in Python

Vivek Singh Bhadauria
Blog
01st Feb, 2018
Create an API Using Flask in Python

In this article, we are going to learn how to create an API using Flask in Python. Before getting into coding the API, I would like to give a brief introduction of the Flask framework for Web services and what an API is.

Flask

It is a microframework for Python based on Werkzeug and Jinja2. Basically, it's a lightweight framework for creating web services using Python. Whereas Django is heavy compared to Flask. Flask is super easy to setup and gets things ready.

API (Application Programming Integration)

API is a code that allows two software programs to communicate with each other. API defines the correct way for a developer to write software that requests for services from other applications. APIs are generally implemented using function calls. API needs to be documented after coding so that developers can read and understand what kind of operation they would do on each function call.

We are going to implement RESTful API using Flask as an example. REST architecture was designed to fit HTTP protocols. Resources are represented by URIs and each resource may be changed or queried on client’s request.

table

Source: miguelgrinberg.com

Implementation

So we have a basic idea of what Flask and API are. We would follow a project-based approach to create an API using the Flask Framework. We would create an API that would give all the image links from the Zeolearn magazine section. You guessed right. We would need to write a bit of scraping code but for this exercise it's minimal. Instead of giving links you can return any other resource as a response to request.

 Above code snippet implements a simple API endpoint at index URI i.e if this web service is hosted at http://example.com and we call the endpoint ‘/’ which is preceded by hosting URL, which finally looks like  http://example.com/  then we would get output as shown in the image below

Implementation

index() function is routed to ‘/’ using app.route(<URI>, <HTTP method>) URI is relative to base URL. Routing is done by using app.route decorator and the decorator simply maps URL to a resource. jsonify() turns json output into a Response object with the application/json mimetype.

We can check HTTP verbs of the incoming request in the following way

We can create Response objects for various mime types in the following way

Output:

Output:

Now we will implement more complex resource URIs. Let's create an endpoint that takes an integer number from request and returns that many number of image urls as a response to the request. As I told you above, we are going to write a little bit of scraping code to extract image URLs from Zeolearn magazines section.

First route function to desired URI, for example, I am routing to ‘/magazine/photos/<number_of_images>’, observe how I put number_of_images inside angular brackets and that's because it a variable, everything variable needs to be put inside angular brackets as they would be changing with different client’s request.

Scraping code used is really simple to understand in this example. I just requested the magazine section of zeolearn and extracted all the image links from img tags in the html page. I used BeautifulSoup module for web scraping. Let's not dive too deep into scraping, the only thing to understand is that you obtained the required data that you want to send as response. Now jsonify the data and send. Response of above endpoint is shown in image below -

We have seen GET requests in the above examples, now let’s see how do we handle POST requests. But before that let’s see how Wikipedia defines these methods-

GET - Requests a representation of a specified resource.

POST - Submits data be processed (e.g. from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updation of existing resource or both.

In the example below, we created a POST method that checks the type of data received whether it is of json type or plain text and returns the data after appending its type. Generally, the database is updated or a new entry is created in the database with the information received in the POST request.

All the arguments used in the curl tool can be referred here.

In general, for the implementations of API, the web service has access to database and queries database based on client’s request. This is, in fact, one of the reasons why REST architecture is preferred. Suppose you want to make Application which stores users data somewhere and the application has different clients like Android, web app, iOS app, etc. So instead of creating a separate backend for each client, we prefer to create an API which serves the data to all the clients. API does this by exposing some endpoints like we created in the example above. We created two end points- one at ‘/’ and other at ‘/magazines/photos/<number of images>’. Clients can make a request to any endpoint to get the response.

Similarly, we can make other endpoints of the API and document them for developers to use it in client-side applications.  

Now you would be understanding why documentation of API is necessary. So that the other developers can look at the documentation and understand what type of data each API endpoint requires and what type of data it returns in response to client’s request.

Vivek Singh

Vivek Singh Bhadauria

Blog Author

Vivek likes to code in C++, Java, automate tasks with Python and loves to make Android Apps. He is an open-source enthusiast and an ex-Google Summer of Code Student developer and currently works as a software developer at Deutsche Bank.

Github - https://github.com/viveksb007/

Leave a Reply

Your email address will not be published. Required fields are marked *

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs