Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Flask Python: REST API & Swagger Documentation Guide

Pedro Martinho
Tiago Franco

April 19, 2024

Min Read
Flask Python: REST API & Swagger Documentation Guide

What is Flask Python?

A framework is a library used by developers to build and maintain reliable and scalable web applications. There are several frameworks available for Python, such as Tornado, Pyramind, and of course, Django (which is often compared with Flask).

Flask(🌶️) is a Python microframework for web development. Despite being built with a small core and considered a very lightweight Web Server Gateway Interface (WSGI), Flask stands out for its easy-to-extend philosophy. It was designed to scale up to complex applications and to support an easy and quick start.

Moreover, another great advantage of Flask is its functionality. Even though it offers suggestions, Flask does not mandatorily require project layouts or other dependencies. Instead, it allows developers to choose the libraries and tools they wish to use and additionally has various extensions available, that are provided by the community.

blue arrow to the left
Imaginary Cloud logo
blue arrow to the left
Imaginary Cloud logo

What is a REST API?

API is an acronym of Application Programming Interface, which means it is basically how you communicate with an application. REST stands for REpresentational State Transfer and corresponds to an architectural style that aims for stateless communications and separates client and server concerns.

The REST API on this exercise will create a fake implementation of CRUD actions over an entity. An API with CRUD allows the Create, Read, Update and Delete operations over the application's elements.

How to make a REST API using Python Flask?

This article will guide you through the first steps to create a REST API using Flask(🌶️).

Below you can see the endpoints you’ll have by the end of the tutorial. The documentation presented is also generated by the application you will create!

Screenshot of Flask Python endpoint documentation.
Screenshot of Flask endpoint documentation.

Technical requirements

You must have Python installed on the current machine. The code presented will consider Python3. If you want to use Python2 and/or are following this procedure in a Windows machine, please follow the instructions presented in the Flask installation guide.

Let’s start by creating a directory to store the project. In the directory you want to have your project, run the following commands on the shell:

We’ve created the flask_demo directory and moved it inside. Before starting to install dependencies, let’s create a virtual environment by running the following command:

This will create a folder into your project with the name .venv. After that, we need to activate the respective environment by running:

This means we are now considering the venv virtual environment when running any Python code. It might be important to specify the environment you are considering when running it in your IDE.

Make sure you have the environment active before following the next steps. You can check if you are inside the environment by looking to the left side of the console. If there’s the virtual environment name inside parentheses, you’re good to go.

If you want to deactivate the environment, just run the following command:

Screenshot of Flask - venv virtual command environment.

Installation Process

Install the Flask package using pip (Python package installer):

At the point of writing, the Flask stable version is 1.1.2. If you want to have the project specifications updated and with the same version as me, you can use a requirements.txt file instead of installing Flask. You can copy the file below to the root directory.


After that, you just need to run the following command:

Now we are ready to start developing our REST API. The usage of the requirements.txt file is widespread and useful in Python projects since it easily allows you to share and have the project with the same packages installed.

Hello World

The first endpoint code:


What?! Is it that simple? Yes, it is! The code is done to have an application with an implemented endpoint. Now we simply have to define the Flask environment variables and see your application ?. Note that you need to be in the folder with the main.py file to run this commands.

Access the link http://localhost:5000/basic_api/hello_world to see the classic message we all love.

REST API with CRUD structure

Now that we have created our first endpoint, let’s get back to this application blog post's main purpose: Have the REST API with the basic CRUD structure. Import request from Flask and add the lines below to the main file to have the CRUD endpoints created for a specific entity:


Now, for each of the routes created different methods are allowed. The following endpoints are available:

  • GET /entities - get list of entities
  • POST / entities - create an entity
  • GET / entities/<entity_id> - get entity information
  • PUT / entities/<entity_id> - update entity
  • DELETE / entities/<entity_id> - delete entity

With this structure, you are ready to create an API with all the complexity you need. This is not the most scalable structure since you consider multiple validations for each route, and the structure is not rigid. In the next sections, we’ll cover a more scalable solution that allows easy documentation creation as you develop your endpoints.

To test how these endpoints are working, you can use a curl request like the one presented below:


This is the result you should get if you run this command on your machine. Make sure the port your application is running on is the same:

 

Flask - curl Request

Another tool that is very useful and common to use in the development of APIs is Postman. If you’ve never used it, we recommend you try it and explore it! It is very powerful and will increase your development to the moon and beyond. 🚀

Blueprints

Before we present other Flask strengths, let’s talk about blueprints. A blueprint is an object very similar to a flask application object, but instead of creating a new one, it allows the extension of the current application. This might be useful if you want to create multiple versions of an API or simply divide services within the same application.

We will use this class type to present different use case scenarios of a Flask application. Let’s convert the code above to be inserted into a blueprint and load into the main application.

Create a new folder blueprints to start inserting blueprints models as we progress in the blog post. Inside create a folder named basic_endpoints and create a file in it named __init__.py:


Now the main.py file just needs to load the created blueprint and register it to the application object:


Now you should have exactly the same endpoints but with the usage of Blueprints.

Jinja Templates for Flask

As already stated, Flask is a very minimal framework; however, it relies on a handy tool: the Jinja template engine. This allows for rendering dynamic HTML templates. Although this is out of this blog post's scope, we will just give a small example to demonstrate the concept.

The first thing you have to do is create the templates folder and inside this folder, insert the example.html file.


Note there are two variables in use in the template inside {{ }}. This is a special format to include Python code inside the template, allowing for dynamic content to be rendered. In this case, we have the top and bottom of the variable, which will be converted to text inside the <p> tag. Now that the template is created let’s load it using Flask. Let’s create a new blueprint in a different file to demonstrate this example:

Do not forget to register this blueprint in the main.py file:


Here we can see the definition of the top and bottom variables based on the query params sent in the URL. For example, if you go to http://localhost:5000/jinja_template?top=top_text&bottom=bottom_text you will get the following result:

Screenshot of result of the top and bottom variables.

Adding CSS

For the giggles, let’s add some CSS to the page we just created. Create the static folder with the file example.css inside.


After that, add the corresponding reference to the CSS file we just created by adding this head tag to the HTML file:


Go to http://localhost:5000/jinja_template?top=cancel%20the%20REST%20API%20creation&bottom=I%20have%20to%20watch%20this%20bird and you should see something like this:

Screenshot of a meme showing a black cat with a yellow necktie with the message "Cancel the Rest API creation, I have to watch this bird" indicating an error.

There! You have your jinja crash course and a meme generator endpoint! Do not touch the Business Cat! You might be surprised with what you'll find...

Digital Transformation Service CTA
blue arrow to the left
Imaginary Cloud logo

How to create a swagger documentation with Flask?

Now that we’ve considered some basic functionalities to have basic endpoints created with Flask, let’s create a better project structure for our endpoints.

Documentation with Swagger

Everyone knows the guy is right, but it can be a boring process. Fear not! With the use of the Flask extension Flask-RESTPlus we can have documentation generated automatically and with a better structure if you follow their recommendations on scalable projects.

To have it installed, just like flask, run the following command:

If you want to have the same flask-restplus version as the point of writing, just add flask-restplus==0.13.0 to the requirements.txt file and install the requirements again. There are some problems related to dependencies, therefore, you have also to install the version 0.16.1 from the Werkzeug package by running:

Let’s now take a look to the project structure we have so far and the one we propose for this blueprint we are creating:

Screenshot of a project structure in Flask.

For the documented endpoints, let’s create a folder to identify the entity we are working on. This will facilitate the navigation through the project as it gets bigger and increasingly more complex. Each of the folders inside the documented_endpoints works like modules with the functionalities/endpoints related to that entity (in this case, users and cats).

We’ll present all the endpoints already created with a new structure. The endpoints will have no logic but will allow you to understand the steps involved in their creation.

With that said, let’s move on to the code. First, we should consider the hello_world endpoint with the new structure:


Now let’s break it down. One of the first things that you might notice is the usage of the Namespace and Resource classes. The Namespace is directly linked to a specific entity, meaning that all the hello_world endpoints will be linked to the corresponding namespace. This will generate the hello_world section in the swagger documentation.

To create routes in this Namespace, different classes that inherit from the Resource class are declared along with the respective namespace route decorator. Within the created HelloWorld class we declare the methods it contemplates. In our case, only GET is presented, resulting in a GET method available for the docummented_endpoints/hello_world endpoint.

The hello_world related models are presented and will be linked to the respective endpoint. This generates the documentation for the endpoint response and marshal the respective response.

The comments associated with the created resources and respective methods will generate descriptions on the final documentation. The possible errors the endpoint can return should also be specified as presented in the example and will also result in further endpoints documentation. There are more functionalities supported by the flask-restplus extension, such as parsers and error handling. Please refer to their documentation if you want to take full advantage of its capabilities.

Now let’s present the code to link this Namespace we have created to a blueprint (blueprints/documented_endpoints/__init__.py) and after that link the blueprint to the application (main.py):


Here, an API object from fask-restplus module is created and linked to the documented_api blueprint. The link between the blueprint and the hello_world namespace we have created is done with this object with the add_namespace method. Finally, just like all the previous blueprints, we just have to register the created blueprint to the app object. Follow the link http://localhost:5000/documented_api/doc and you'll get this page:

Flask Rest plus Demo to present the code for the documentation so any person can check all the endpoints.

Now let’s present the code for the documentation of the entities REST API and jinja template page so any person can easily check all the endpoints we’ve been working on. This is done by adding the following files:


Even though these files might look scary, the logic is the same as the one presented for the hello world endpoint. The main difference is the usage of models to generate documentation and validate the request body sent in POST and PUT methods. Parsers are also used for the query params documentation and can also be used for validation. This is useful for scenarios in which the data is not sent via body, such as query params or FormData.

Last but not least, do not forget to add the following lines to have the created namespaces linked to the Blueprint we are creating.

Bellow, you can check the documentation appearance for query params and a request body:

Documentation for query params and request body

Now we have the documentation of all the endpoints and the respective endpoints (of course!!).

blue arrow to the left
Imaginary Cloud logo

Conclusion

Despite its simplicity, Flask is an extremely powerful Python web framework. It is much easier and more straightforward than creating complete server-side applications. Plus, it can save you so much time!

Hopefully, by the end of this article, you will have no trouble creating a REST API using Flask and automatically generating a swagger documentation page. Additionally, you should be familiar with specific functions (such as Blueprint objects) and setting up Jinja templates.

FAQ (Frequently Asked Questions)

What is Flask?

Flask is a lightweight WSGI web application framework in Python designed to make getting started quick and easy, with the ability to scale up to complex applications.

What is Flask in Python used for?

Flask is used for creating web applications ranging from simple web pages to complex, database-driven sites. It is particularly favored for building web APIs, microservices, and serving web pages for dynamic content.

Is Flask suitable for beginners?

A3: Yes, Flask is considered beginner-friendly due to its simplicity and ease of use. It allows newcomers to start with simple applications and gradually move to more complex ones.

Is Flask or Django better?

Whether Flask or Django is "better" depends on the project requirements and the developer's preference. Flask is more flexible and minimalist, while Django offers more built-in features. Flask is often chosen for smaller projects or when more control is needed, while Django is selected for larger applications with more out-of-the-box functionality.

Can Flask be used for large-scale applications?

A6: While Flask is lightweight, it can be scaled to support large-scale applications by using additional tools and libraries to handle more complex requirements.

Is Flask a frontend or backend?

Flask is a backend framework. It is used to create the server-side of web applications and APIs, although it can serve HTML, CSS, and JavaScript files to the frontend.

Is Flask a coding language?

No, Flask is not a coding language. It is a web framework written in the Python programming language and is used to develop web applications.

How do I install Flask?

Flask can be installed using pip, the Python package manager, with the command pip install Flask.

Can Flask be used with frontend frameworks like React or Vue?

Yes, Flask can serve as a backend API and can be integrated with frontend frameworks to create full-stack applications.

What are some common use cases for Flask?

Flask is commonly used for building web applications, microservices, APIs, and as a part of larger applications where a lightweight web interface is needed.

How does Flask handle routing?

Flask handles routing with decorators that bind functions to URL patterns, making URL creation easy and intuitive.

Build scalable products with Web & Mobile Development

Found this article useful? You might like these ones too!

blue arrow to the left
Imaginary Cloud logo
blue arrow to the left
Imaginary Cloud logo
blue arrow to the left
Imaginary Cloud logo
blue arrow to the left
Imaginary Cloud logo
blue arrow to the left
Imaginary Cloud logo
blue arrow to the left
Imaginary Cloud logo
Pedro Martinho
Pedro Martinho

Associate developer working mostly with Backend technologies. An entrepreneur with Data Science interest. Love for sports, audiobooks, coffee and memes!

Read more posts by this author
Tiago Franco
Tiago Franco

CEO @ Imaginary Cloud and co-author of the Product Design Process book. I enjoy food, wine, and Krav Maga (not necessarily in this order).

Read more posts by this author

People who read this post, also found these interesting:

arrow left
arrow to the right
Dropdown caret icon