Understanding RESTful API with Flask

Nishant Joshi
Analytics Vidhya
Published in
8 min readApr 6, 2020

--

This is going to be a write up on how to make your REST APIs using a simple yet powerful framework named Flask. APIs accomplish various tasks for developers and end-users, as they abstract must of querying and make it easy to interact with the base system which could be your server or a database.

What are RESTful APIs

REST is an acronym for REpresentational State Transfer. It is an architectural style for distributed hypermedia systems. By separating the user interface concerns from the data storage concerns it improves the portability of the user interface across multiple platforms and improves scalability by simplifying the server components.
Ok, so what does it mean, in simple terms, the server provides endpoint similar to a URL where you could ask for or put data. It abstracts the hassle of making you on integration software by providing endpoints to make it easily accessible, usable and can integrate with other applications easily.

Implementations with example

Enough with the history, and theory, let dig in.
For this implementation we are going to use Flask, this is going to be a very simplified explanation of API, there are extinctions for Flask to make API, but we are going old school and building them by hand.

Installation

Here we are going to use Flask which is a module of python. The code snippets that are present below will follow the python3 syntax.

  • You are required to have python installed
  • If you prefer you can create a virtual environment to go along with the package installation. you can get more information on VEnv here
  • After that, you are ready to install the module.
# ------------------------------------------------
# If you are using python3
>> >> >> $ pip3 install Flask
# ------------------------------------------------
# ------------------------------------------------
# If you are using python
>> >> >> $ pip install Flask
# ------------------------------------------------
  • The last thing that you need is creativity, but seeing you are here you have plenty of that already

Simple Example

Well now look at that, it feels pretty simple to make a GET request. Ignore the emojis and the comments, they are there to provide help.
Now, let’s go over each line of code:

  1. from flask import Flask :
    This is just getting the constructor for the main class Flask from the library flask
  2. app = Flask(__name__) :
    This is creating your web application with the name of the running program that is __main__ if you are going to run the file
  3. @app.route("/", methods=["GET"]) :
    This is a decorator it is what we can call a wrapper over the function below it, but in this context, it means any request the is directed towards the endpoint “/” of type “GET” will be resolved by the function that is written below it.
  4. def root():
    return "This is root\n"
    :
    This is the resolver function that resolves any request that is sent to “/”.
  5. This last part just ensures that the application is hosted where we run the file
  6. Now, to see the results just run the file containing the code above using a command like python3 app.py where app.py is the name of the file. In the terminal, it will display a URL
# In my case it was http://127.0.0.1:5000/
# Just open this link in your browser and the your put will not shock you: it is indeed "This is root" the \n is just to make to readable your you are familier with curl.

Requests

Now let get started with making the requests, now if you want to write the code and see the results alongside, in the example above just change app.run() => app.run(debug=True)
This will automatically apply the changes you do in the application file to the app. But save only after all the syntactical errors are cleared or else the program will exit and you will have to start it again, same as the step. 6 from the example above. The examples that are available below are the continuation of the code above to make it easier to understand.
If you are going to try the example add the code that is going to be available below before the statement if __name__ == "__main__": to implement the code.

GET Request

We are going to understand more about this GET request as we go further.

What is GET Request ?
Get request are use to get data from specific resource it is a simple way of querying the endpoint.
- Get request are similar to our normal http request but instead of serving web page content we get data in form for json, xml.
- You can also pass arguments to the GET request to specify you requirement.
A similar example would be : https://www.google.com/search?q=what+is+restful+api
Here:
route (endpoint) => “/search”,
arguments => q : value = > “what is restful api”

I have written that we can pass arguments to the GET request but how can you fetch it: for this purpose we need a function.
from flask import request we already imported Flask from this model.
To access these arguments that are passed by the get requests are accessed using request.args this is a data type that can be cast to the dictionary.

Example

In the above example, I have a global variable named registry which is a list containing the name & ages of people. This complete code is present below if you want to check it out. jsonify is a function provided by the flask library that converts dictionary, list, etc data types into strings to be safely sent back as a response.

POST Request

What is POST Request ?
POST is used to send data to a server to create/update a resource.
Here the data that is sent is not appended to the URL neither it is cached or stored thus it makes is more secure to give data back to the server and makes it easier to parse it. Usually the data that is given to the API is in JSON (JavaScript Object Notation) format. Thus we use the object request.json to get the data that is posted.

Example

If you are new to this whole concept of API you might find it disturbing that we have used the same endpoint “/registry” for making the get request.
Well, don’t be we can use a single endpoint for making multiple requests depending upon the method like GET, POST, PUT, DELETE, so one endpoint can have any number of methods.
If you were to implement such a concept you can use request.method to identify the method of the current request passed to the resolver function, I could have implemented it but it would not have been clear if I have done so.

Now the question is how are you going to test it? We can just enter the URL with the arguments in the web browser to test our GET method, but it is not that simple for the other methods. To implement this you could use https://www.postman.com/ which is a great resource for testing various API’s or you could use $ curl which is a Linux command. Maybe you could also use the python module requests for this purpose, it’s your choice.

URL Converters

This is a feature that will come in handy which creating an API.
In the picture above I have used it with the GET method but it can work with any other method as well you will see it as we go.
— Now, what is different is the code above, firstly the endpoint is different, I could call it weird, what is that <string:name> anyway.
Well, this is the URL converter it is a place holder for any string that does not contain a backslash.
— This second key difference is the resolver function has an argument, this argument receives the value that is placed at <string:name> .

There are various place holders for different purposes.

The own mentioned above are some of the default types that can be used.
Like => <type:variable_name>

You can also create your custom types using the tools provided by the flask library.

PUT Request

Now, I am not going to tell you any different about this request, because it is similar to that of POST, but the purpose of this request is to specifically update, or create a new entry, POST request could have different uses, but the documentation says to use them only to alter entry/or create new once for a specific resource.
The goal of this request to make it so that the output after this API is called is idempotent.
This is similar to POST in getting data and using accessing it.

DELETE Request

Here this is one of the dangerous API as without any authentication anyone can delete any entry for the DB they desire. But implementing all these APIs in your project at the same time is not at all important and would be a waste of resources, this is just for explanation purposes.

The DELETE method deletes an entry that is present at a specified resource based on the URL of the link. The prime goal of this method is to record this act as deleting, but the same can be accomplished using POST, just by specifying the right conditions and endpoints.

Source Code for the Example

Thank you for reading so far, I dearly hope you learned something from this article, keep learning and all the best!!

--

--

Nishant Joshi
Analytics Vidhya

Developer, Programmer, learner, and curious human being