avatarJulie Perilla Garcia

Summarize

A Simple Guide to Building Your First Python Flask API

Photo by Sharon McCutcheon on Unsplash

Python’s Flask is a lightweight web framework that provides a way to quickly build a backend for your application while giving the developer control over the implementation. It was created a few years after Django became popular, so it improves upon Django in many ways, while allowing for greater flexibility.

Unlike Django, Flask does not provide a built-in data access layer or migrations, administration interface, serialization, caching, or form validation methods. It does provide a template engine, development server and debugger, unit testing, and built-in support for working with HTTP requests and responses.

If you dislike boilerplate code, want more flexibility in your implementation, and want to get started quickly, Flask is a great choice.

In this guide, I describe how to get a simple Python Flask API set up in minutes. In future tutorials, I will do a deep dive into the different elements of the Flask framework.

Set Up Your Python Virtual Environment

Python virtual environments act as containers that allow you to run your Flask application in isolation. If you haven’t yet set up a Python virtual environment, you can find out how with this guide. This step is not necessary, but it will make your life a lot easier if you are managing multiple projects.

Install Flask

Next, install the Flask framework package using pip. Make sure that your virtual environment is activated, then run the following commands. These commands install flask and then save the requirement to your requirements.txt file.

pip install flask
pip freeze > requirements.txt

Create a Basic Flask Application

Creating a Flask application is as easy as adding one file with two lines of code. First, create a directory to store your new application. Then create the app.py file. The one I’m building is one to manage recipes, so I called my directory recipes-api.

mkdir recipes-api
touch app.py

Open the app.py file and add the following code.

from flask import Flask
app = Flask(__name__)

You now have a Flask API. It has no routes, though, so let’s take care of that.

Create Your Routes

Flask routes correspond to API endpoints that can be called via HTTP GET, POST, PUT and DELETE commands. Your routes are the consumer’s view of what your API can do, so they should be meaningful to the programmer calling them and follow REST principles.

Let’s add two routes; one that serves as the home page for my API in a browser, and one that gets all recipes. For now, I return dummy data. In a later tutorial, I cover fetching data from a database with SQLAlchemy.

The @app.route decorator is used to tell Flask which route should call this particular function. Inside the function, return the data. To keep it simple, we only return raw data, for now, leaving out HTTP status codes.

@app.route('/')
def index():
  return '<h1>Recipes API</h1>'
@app.route('/recipes')
def recipes():
  return {
    'title': 'Smoked Salmon Chowder', 
    'ingredients': 'salmon, milk, bacon'
  }

Run Your Application

The Flask framework provides a simple development web server. This convenient feature is a single-threaded server that is not suitable for production environments. If you need to run your application in production now, see these deployment options.

For now, we use the following commands to run our application locally.

flask run

Flask automatically detects the app.py file (you could also name it wsgi.py) and finds the flask app inside. Be aware that this file must be located in the directory where you are running the flask command, so I generally put it in the root directory of my project. Also, if you name your file something other than app.py or wsgi.py, you need to tell Flask where your app resides by setting the FLASK_APP environment variable.

export FLASK_APP=my_app.py

You should see this when you run your flask application.

Navigate to http://127.0.0.1:5000/ or http://localhost:5000/ in your browser, and you should see your home page.

Try navigating to http://localhost:5000/recipes, and you should see your data returned.

Congrats! You just built a Flask API.

(Bonus) Use Debug Mode

To run your application in debug mode and take advantage of Flask’s built-in reloading feature, set the FLASK_DEBUG=1 environment variable and then rerun the flask command.

export FLASK_DEBUG=1
flask run

Now you should see something like this in your terminal, with Debug mode set to on.

If you have a browser open and you change something in your app.py file, for example, the text that is returned by your route, you should see the server rebuild your application.

Flask won’t reload your browser automatically. If you want traditional hot reloading that you would see with a frontend application, try installing a package like python-livereload.

(Bonus) Setup a .env File

Flask automatically recognizes a .env file in your root directory. To avoid having to set the above environment variables every time you start your virtual environment, create a .env file.

FLASK_APP=path/to/your/app
FLASK_DEBUG=1

For Flask to recognize this, you first need to install the python-dotenv package.

pip install python-dotenv
pip freeze > requirements.txt

Now deactivate and reactivate your virtual environment. Typically, you would have to reset the Flask environment variables. This time, Flask picks them up automatically.

flask run

That’s all you need to get started. Now you can start building out more routes and adding your business logic. I will go into more detail in future posts. Happy coding!

Resources

Python
Flask
Programming
API
Web Development
Recommended from ReadMedium