How to build a simple web API in a few minutes using Python and Flask

Let’s say you want to build an API that calculates something to be used in a web or mobile app, something that doesn’t need databases or page templates.
Flask is great for that, and in this article I’ll explain how you can build a web API that listens on a port and calculates the nth Fibonacci number based on GET Request parameters.

Carmine Zaccagnino
Jun 13, 2018 · 3 min read

Installing everything we’ll need

First off, you should download Python and pip using the normal installation procedure for your operating system.
Then, open up a terminal window (a Command Prompt on Windows) and install Flask and its dependencies by using the command

pip install Flask

Starting our project

With Flask, starting a project is as simple as creating a Python file in any folder you want your code to be, so once Flask is installed, navigate to the folder where you want your API code to be and create a file with a .py extension.
I’ll call this file , so if you want to copy and paste every command in this article, you should give it the same name.

The code we need to get started

The first line of our project will be importing the only dependency for our project: the Flask framework itself:

from flask import Flask

On the next line we create an app instance of Flask (respecting common naming conventions you might find on other documentation)

app = Flask(__name__)

That’s everything we need to start actually writing the code that is necessary for our application to be useful.

Building the actual API

The Fibonacci number function itself

As I said at the top of the article, this example app will output a Fibonacci number, so we need to implement the function that does the actual calculations.
I will use the simplest normal recursive implementation that shouldn’t ever end with infinite recursion

def fibo(n):
if n < 1:
return 0
elif n == 1:
return 1
return fibo(n-1)+fibo(n-2)

I will not go into it since this falls outside the scope of the article.
Just to make everything clear, fibo(1) outputs the first number of the sequence, fibo(2) the second, etc…

The Flask route to manage requests

Creating a route (an endpoint) for your application is very simple:

@app.route("/") # To make our site available at URL:port/
def send_fibo():
return str(fibo(int(request.args['n']))) # getting the argument called "n", converting it to the string, giving it to fibo and converting the output to a string

This will work if you try to run this with (replace with the name of the file you created if you chose a different name) flask run

and you go to your browser and navigate to, for example, http://localhost:5000/?n=15 , but there are a few issues: if there is no argument called “n”, we will get a Bad Request response, and that is acceptable, since a request without the number would indeed be malformed or impossible to do anything with to say the least, but there is another problem: if the n parameter is not a number, you will get an Internal Server Error, while a custom message should probably be more appropriate.
To do this, we need to catch the error that is thrown, in this case a ValueError, so we’ll change send_fibo() to

return str(fibo(int(request.args[‘n’])))
except ValueError:
return “Please use a number as the ’n’ argument”

If you run this, it will display our error message when the user inserts improper input.
The final program code, with docstrings and type annotations, is:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade