Python FastAPI crash course

Here is a crash course (series of articles) that will allow you to create an API in Python with FastAPI.

I will publish a new article about every two days and little by little you will learn everything there is to know about FastAPI

To not miss anything follow me on twitter: https://twitter.com/EricTheCoder_

What is FastAPI?

FastAPI is a Python web framework that allows you to quickly build high performance APIs.

Why FastAPI?

Before FastAPI there were already several ways to create APIs with Python. Especially with Django Rest Framework and Flask. So why FastAPI?

Here is the list of the main advantages of FastAPI:

  • Very fast: The performance is superior to Django and Flask and is even comparable to the performance of NodeJS and GO
  • Fast to code: Build APIs 2-3 times faster
  • Easy: Easy to use and learn
  • Type annotation (Type hints): Facilitates validation, allows auto-completion and facilitates debugging
  • Automatic documentation: FastAPI generates documentation in Swagger UI and ReDoc format automatically.

Pre-requisites

To start coding with FastAPI you must have a basic programming knowledge with the Python language.

You should also make sure that you have an updated version of Python (version 3.6 or +)

From the terminal type this command to find out the version of Python installed on your machine.

$ python --version

or

$ python3 --version

If you don't have Python or a version earlier than 3.6, you can get the latest version of Python from the official website: https://www.python.org/downloads/

Code editor

For this tutorial, I'll be using Visual Studio Code: https://code.visualstudio.com/

It will be easier for you to follow me with this editor but it is really not a requirement.

Finally, if you are using vscode, make sure the Python extension is installed.

Creation of the virtual environment

When working on a Python project, we have to work with several libraries like FastAPI, Flask or Django, etc.

According to the date of creation of the project. It is possible for example that the FastAPI library is not exactly at the same version number in the other projects.

How to allow each project to have its own version of Python and its own versions of libraries?

We will be using virtual environments.

A virtual environment allows you to install Python and python libraries in a folder / project without this affecting the other folders / projects.

Python provides you with a system that allows you to create virtual environments.

Once the environment has been created and activated, all the libraries installed can be used only in the environment to which they belong.

How to create a virtual environment

Normally we place a virtual environment in the project folder.

Create and access a folder for our project

$ mkdir fastapi-demo
$ cd fastapi-demo

From this folder you can now create the virtual environment that will be attached to the project

$ python3 -m venv env

Here we launch python3 with the module option venv. env is the name we give to our virtual environment.

Once the virtual environment has been created, you can activate it:

MacOS / Linux

$ source env/bin/activate

Windows

$ env\Scripts\activate.bat

That's it that's all ! You now have a Python virtual environment created for your project. Normally the terminal will tell you that your environment is activated by displaying its name.

Note that to deactivate the virtual environment you must run

$ deactivate

For the rest of the tutorial, make sure the virtual environment is enabled before running any commands in the terminal.

Installing FastAPI

From the fastapi-demo folder and with the virtual environment enabled, run the following installation command:

$ pip install "fastapi[all]"

This command will install FastAPI and also install some optional dependencies like local server (uvicorn) to test FastAPi on your machine.

Once these libraries are installed, you can launch your open code editor on the current folder

$ code .

This command will launch Visual Studio Code open on the current folder

Reminder: What is an API?

API stands for Application Programming Interface.

In short, it is a program that can be used by another program, in order to allow applications to communicate with each other.

An API allows the server and the client to communicate with each other and to exchange information and data. The data exchanged is in structured text format (JSON).

The exchanges are made in the form of requests and responses:!Alt Text

For example, the browser (client / frontend application) makes a specific request to a server:

GET www.example.com/products/3814

Can the server know how to handle this request? He can't. He won't know what to do with the request.

That's why we need to create an API. This is a server application that will determine how to respond to various requests for a specific resource.

Let's go back to the last example query:

GET www.example.com/products/3814

The customer wishes to obtain the information of the product no 3814

To respond to this request, we could create an API that would search for the 3814 product in a database and return this response to the customer in structured text (JSON) format.

{
  "id": 3814,
  "name": "iPhone 12",
  "qty": 29,
  "price": 799
}

Different type of requests

Note that all requests to servers are made through HTTP actions.

Here are the most commonly used HTTP actions

GET: GET requests are only used to retrieve data.

POST: POST requests are used to send data.

PUT: PUT requests are used to modify data.

PATCH: PATCH requests are used to partially modify data.

DELETE: DELETE requests are used to delete the specified data.

When we are dealing with a resource. For example Product. Each action on the Product resource has its own route

Here is an example route for each of the HTTP actions:

Create : POST www.example.com/

Read : GET www.example.com/products/3814

Update : PUT www.example.com/products/3814

Destroy : DELETE www.example.com/products/3814

The way to name these routes is no accident, it is in fact a convention that is followed by most developers.

Your first API

The theory is over, now let's see how to create your first API

From the code editor create a file named: first-api.py

Enter this code

from fastapi import FastAPI

app = FastAPI()

@app.get("/home")
def index():
    return {"message": "Hello World"}

app = FastAPI() allows to create an instance of FastAPI

The @app.get() decorator allows us to specify the url path and the HTTP (GET) action of our api.

The index() function will be executed each time a user visits the URL path specified by the @app.get() decorator, in this case the "/home" path

Note that the name of the "index()" function could be any name. It is according to your preference.

To start the server and test your first API, enter in the terminal

$ uvicorn first-api:app --reload

uvicorn is the local server. It takes as parameter the name of the file: the name of the FastAPI instance

The —reload option will restart the server each time the source file is modified.

So you can then visit: http://127.0.0.1:8000/home

The following response will be displayed:

{
  "message": "Hello World"
}

Well done! You have just created your first API

Last point. The path you created points to "http://127.0.0.1:8000/home". How to make it point to the "root path" aka "http://127.0.0.1:8000"

You must only use a back slash "/"

@app.get("/")

The back slash used alone means "root path"

Conclusion

That's all for today, follow me on twitter: https://twitter.com/EricTheCoder_ to be notified of the publication of the next article (within two days).

32