👨🏼‍💻FastAPI | Review with a fast simple example

Nabi GĂĽzel
Huawei Developers
Published in
6 min readJul 1, 2022
FastAPI framework, high performance, easy to learn, fast to code, ready for production

Introduction

Hi everyone,

I’ve heard of FastAPI framework technology in a few places before, I recently had the opportunity to examine it basically and create a simple example. In this article, I compile and share the notes that I took during the working process with the thought that they will be useful for someone.

What is this FastAPI?

In their own words, this is a library that “FastAPI framework, high performance, easy to learn, fast to code, ready for production.”.

How can I set up FastAPI?

To install FastAPI, you must first have an equivalent of the “pip -V” command on your computer. To install it, you can follow the steps on the documentation site at “pip.pypa.io”.

After the “pip” installation is complete, the command you need to run to install FastAPI is :

pip install fastapi

You will also need a local server. The command you need to run for installation of the local server is:

pip install "uvicorn[standart]"

Creating and Running a Project

After the installations are completed, let’s open a project folder and create a “main.py” file in it. (At the end of the article, I shared the gist of the “main.py” file I created for this study, containing the codes as a whole.)

After creating the file, we need to run a server that allows us to instantly test the changes we will make during the development process. Here’s the command you should run for a server that detects instant changes:

uvicorn main:app --reload

Project Structure

In this project, I only develop from a single file. I aim to create basically GET, POST, PUT, and DELETE requests, so I have handled the classic “Todo” application.

Optionally, a file hierarchy structure could create under this folder according to its progress. For example, “routing” clustering can be created in different files under a folder named “routers”.

How do I write Hello World?

“Hello World” is the first coding test for a new language or technology to learn. :) In the code below I created for this purpose, I basically created a GET request. At the same time, FastAPI automatically created a document page with a Swagger interface.

We can open the swagger file by adding “/docs” to the end of the local working link, which is written on the command screen (cmd, terminal) after the server starts. For example:

http://127.0.0.1:8000/docs

How can I implement Swagger features for the documentation?

If the function name in the above example is “camelCase”, it would read “Saygreeting” as seen below in the document, but if I had written it as “say_greeting”, it would have written, “Say Greeting”.

Instead of writing the function names according to what I have specified above, we can write them as we want. For this, we can use the “summary” parameter as a second parameter where we write the request type as the below example since FastAPI is an OpenAPI 3.0 compatible.

@app.get("/", summary="Say Greeting")

You can review the Swagger documentation for other parameters that can be used.

http://127.0.0.1:8000/docs

How do I write CRUD?

In this study, I have written requests that will create an empty array and perform the commands for adding, listing, updating, and deleting without using any database for now.

How do I determine the request type (GET, POST, PUT, DEL)?

First of all, the type of request is determined by the part written on the function that will perform the relevant operation. As in the example above, we can understand that the function written just below the “@app.get(“/”) can be accessed with a GET request.

For “query” variable parameters such as “id”, it will be sufficient to write them in curly brackets.

In addition, we can use the “tags” parameter to group the requests we write in the swagger document. For example, in order to group the requests under “todo”, it was enough to add the “tags” parameter to the request type and add “Todo” to the request type, as shown in the image below.

How can I define parameters (path, query, body)?

We can specify whether the type of parameter that will come to the function is “Path” or “Query” as a function parameter, as in the use of “Path” in the “getTodoDetail” function in the example above. You can also write the note you want to appear next to the parameter using the “description” parameter in “Query” or “Path”.

Description text representation of “getToDetail” function with using the parameter “description”
“TodoCreate” parameter that sent with “Body”

How can I set the validations?

In requests such as “Post”, “Patch”, and “Put”, we can determine what the object type that will come as the “body” element of the request will be, by assigning the relevant object in the parameter. In addition, this determination activates automatic validation. For example, when I run a post request that contains a “title” element value with longer than 20 characters in the body, the system automatically returned the following error to me, because the “title” has a maximum limit of 20 characters limitation.

We can determine the return type with the “JSON” structure by writing directly, or we can also determine the “status” value of the return by using the “JSONResponse” in the “get” code image above.

Although it is about “python”, not FastAPI, I write this as a note; In the part that starts with “… next(filter(lambda…”) written in the “getTodoDetail” function, a single element is returned as a result of the filtering, by using “next” statement. When I wish that it returns as a list, I must write the expression “list” as in the “getTodoList” function, as in “… list(filter(lambda…”).

How can I write models?

Restrictions on the request to be used are made on the model, and it is necessary to write a special model for the relevant request.

For example, I set the “Update” model as a BaseModel because all the parameters to be included here are optional in the update. So the user may only want to update on the non-mandatory parameter “tags”. Also, I didn’t write the “id” value in the Update model because the user should not be able to access this parameter in the update. If you pay attention to the model parameters I created for “Create”, I removed their optional status, so the user has to send those parameters.

Output

When we combine the codes I gave above piece by piece, we get a code like a gist document below. In addition, when we run this code, we can access the following Swagger document interface from the browser.

The document output of “main.py”
The “main.py” file containing all the code I’ve worked on

Conclusion

As you can see, creating service requests with FastAPI is quite simple. After this stage, it is possible to produce a more useful project quickly by adding the coding that includes our own logical operations. For example; We can add a database integration and easily add codes that will perform processes on that database.

Good coding…

--

--