Follow these few easy steps to program a basic API using Flask

As we know, Python is a programming language that makes use of frameworks to create a number of web applications, websites, APIs, and desktop applications. But what actually is a framework? A framework is a collection of libraries and modules that help developers create complex, scalable, maintainable, and reliable applications. A Framework usually helps in providing reusable code and extensions. As we’ve covered previously, some Python frameworks include Flask, Tornado, Pyramid, and Django. Below, we’ll see where Flask shines and outline how to use it to create a simple API in Python.

Introduction to Flask

First of all, what is Flask? Flask is basically a micro web application framework written in Python. Developers often use Flask for making web applications, HTTP request management, and template rendering. By “micro web application,” we mean that it is not a full-stack framework.

The term micro refers to making the core part simple and rather extensible. Since Flask is lightweight, it’s easy to work with on any project — it’s easier to find mistakes and fix errors than a full-stack framework. You can use Flask to create impressive products also. Many big companies like Netflix, LinkedIn, Pinterest, Twilio, Uber, and Dropbox use Flask.

Now the next question arises: If we are already using the Django framework, which is famous for making web applications and APIs because of its set project structure and inbuilt tools, then why do we need Flask? Well, Flask could be more useful compared to Django because it’s like an empty canvas to create Python-based applications — it doesn’t have a project layout and has few dependencies. Flask can provide suggestions for libraries and tools to be used for development purposes.

Coming to the history of Flask, it was launched as an April fool’s joke in 2010 by Armin Ronacher, who leads a Python group named Pocco. It was not that much popular at the time of development, but in a 2018 Python Developers survey, Flask received much fanfare. By January 2020, it had become very popular on GitHub. Flask is based on Werkzeug, WSGI toolkit, and Jinja2 engine, which are Pocco projects.

  • Werkzeug: Used by Flask framework as one of its bases for implementing requests, response objects, and other utility functions.
  • Jinja2: A templating engine used in Python to combine it with data sources and obtain dynamic web pages.
  • WSGI: A Web Server Gateway Interface. Using WSGI is standard for web application development in Python.

Flask Features

Some important features of Flask are as follows:

  • Flask has its own development server to run any application and debugger that refreshes the server when you make code changes. The server is only meant to be used for development and not for deployment.
  • It supports Jinja2, which is designer-friendly and allows secure sandboxed execution. Templating and Jinja allow for easy exchange of data between frontend and backend. So it is a kind of Bridge in Flask.
  • It is based on a Werkzeug WSGI tool that provides a web server gateway interface to communicate between a web server and web application.
  • It supports cookies and sessions so that it can make an Internet browsing experience better.
  • It also provides extensive documentation with examples to reference when you need help.
  • Flask classes allow extensions like database library, upload handling, form validation, and open authentication technologies.
  • Easy boilerplate code for app creation and running makes Flask a better web framework choice than Django.

Comparison of Flask and Django

A web developer has several options to choose from for web frameworks when using Python as a server-side programming language. They can either choose a full-stack web framework like Django or a micro web framework for making simple web applications, like Flask. Both are popular options, so here are the benefits and drawbacks of both options:

  • Being a full-stack Python web framework, Django makes it easier to perform user authentication, URL routing, and database structure migration-related tasks. On the other hand, Flask’s simplicity keeps a web application’s core simple and extensible.
  • Django provides a ready to use admin framework, but that facility is not available in Flask.
  • Flask is based on the Jinja2 template that is inspired by the Django template.
  • Django is also providing a built-in bootstrapping tool to start web applications, but Flask does not.
  • Flask does not provide built-in ORM for database support, while Django does.

Both of these web frameworks are popular options but have pros and cons too. So it is up to the developer to keep in mind the requirements of client projects to make better use of technology. The Django features provide the facility to create large complex projects, while Flask facilitates simpler web applications by providing required functionality only.

Now that we understand Flask let’s dive into the coding part.

Prerequisites:

  • Python
  • Virtualenv

Step 1: Flask Installation and Server Setup

We are assuming that you have already installed Python, and it’s up to date. So let’s set up our project and set up a virtual environment.

Why do we need a virtual environment?

A virtual environment is used to create an isolated Python environment for different projects. We create virtual environments because different projects have different dependencies. Also, it helps to keep the global packages folder clean.

So now open the terminal type the below command:

pip3 install virtualenv

Once it’s installed, let’s create a directory or folder for your project. We are using flask-test as the folder name, but you can pick any name for your project.

mkdir flask-test

Then, change the directory:

cd flask-test

Now it’s time to create a virtual environment for our project so that the dependencies don’t mess up the global package folder.

Execute the below command now:

virtualenv .

And then,

source bin/activate

Explanation: What we are doing here is we are telling the module that the current folder can be used for the virtual environment, and then it is activating the virtual environment in the second step.

Now once you have activated the virtual environment, let’s install the Flask package in that environment.

Now run the below command:

Python3 -m pip install Flask

So far, we have created our project folder, installed and created a virtual environment for our project, and installed Flask in the environment. Let’s head towards Step 2.

Step 2: Let’s Write Some Code

Now create a file app.py and paste the below code:

from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'This is my first API call!'

Make sure to save your app.py file to the current directory.

Code Explanation: First, we are importing the flask module into our application and then defining the API route. The @ is used for defining the API route. We’re passing /, which means this is our base route.

Step 3: Running the Server and Making the First API Call

Once you’re done with the coding part, it’s time to run our Flask server and make our first API call.

To run the server, execute the below command:

flask run

You should see the below output on the terminal:

* Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now open your favorite API testing tool. We’ll be using Postman in the tutorial below, but you can pick any of the tools mentioned here.

Now copy and paste the URL printed on the terminal and make a GET request. You should see the below output:

Using Postman to send a GET call to our Flask API

TADA! Congratulations, you have made your first API call. Now let’s make some APIs based on different methods like POST.

Step 4: POST APIs

Flask makes it very easy to program different commands for various HTTP methods like POST, GET, PUT, etc. In the above code, you can see there’s the function route. The second parameter passed to this function is actually the method of the route. If nothing is passed then, it is GET.

But we also have to import two additional modules named request and jsonify used to fetch the params and JSON conversion.

Now lets define another route for our POST requests. So open the app.py file and replace the existing code with the below code:

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'This is my first API call!'

@app.route('/post', methods=["POST"])
def testpost():
     input_json = request.get_json(force=True) 
     dictToReturn = {'text':input_json['text']}
     return jsonify(dictToReturn)

Code Explanation: Here, we have imported some more modules from Flask, like request and jsonify. We are using request to get the data which the user is sending, and we’re using jsonify for converting dictionaries to JSON. We have added one more route that is /post and also passing POST as a list and returning back what the user is sending in the parameters.

Now once again head over to the API testing tool and hit URL:
http://127.0.0.1:5000/post with parameters:

{
    "text": "Post Example"
}

Since we edited app.py, before you run a POST API call, you will need to restart the virtual server. To do so, (Press CTRL+C to quit), and then enter flask run into the Terminal again.

You should see the below response:

Sending a POST call to our local Flask API

A Basic API With Flask

Now we’re done with the most basic Flask tutorial with one GET and one POST API endpoint. This tutorial was just a gist so that you can understand the basics of Flask.

Flask is a very powerful tool, and on an advanced level, you can achieve a lot of things with it. For example, you could add authentication with JWT or OAuth. You can also connect the code with a MySQL backend and perform CRUD operations.

I hope you learned something new from this article, and hopefully, I made it easier for you to understand Flask and API creation basics.

Vyom Srivastava

Vyom is an enthusiastic full-time coder and also writes at GeekyHumans. With more than 2 years of experience, he has worked on many technologies like Apache Jmeter, Google Puppeteer, Selenium, etc. He also has experience in web development and has created a bunch of websites as a freelancer.