Basic guide for FastAPI framework from A – Z (Part 1)

Tram Ho

Introduction

Hello everyone, today I would like to introduce to you a framework API that I just scratched a few weeks ago. Why do I recommend this framework, this is because the slogan of this team is so eye-catching.

FastAPI framework, high performance, easy to learn, fast to code, ready for production

So what is fastAPI, please read the next section.

Concept

FastApi is a web framework used to build a high performance API, easy to code, simple but also good support for making products.

Characteristics:

  • Fast : Performance is as high as NodeJS and Go.
  • Fast to code : Faster code, speed of code features increase about 200 to 300%.
  • Fewer bugs : By simplicity, reduce the number of developper bugs by 40%.
  • Intuitive : easier code support with auto-suggestion, and debugging took less time than before.
  • Easy : designed to be easy to use and easy to learn.
  • Short : Minimal code iteration. The passed parameters have many features. Little bugs.
  • Robust : powerful performance, interoperable API via docs.

Setting

Requirements: Python 3.6+.

FastAPI is based on OpenAPI (formerly called Swagger), the web part is supported by Starlette, while the data is supported by Pydantic.

FastAPI CLI

To install this framework on Ubuntu, you need a python version geq 3.6.

You also need an ASGI server when deploying a product like Uvicorn or Hypercorn.

A little bit about ASGI, ASGI inherits from WSGI. WSGI is a communication standard between web server and Python application server. Previously, there was mod_python of Apache, but because it was not developed and not safe, WSGI was born. WSGI has the following effects:

  • WSGI is flexible: developers can convert web components like Gunicorn to uWSGI.
  • WSGI processes many requests at the same time replacing the webserver and decides which request is passed to the web application. The illustration of stealing at the page ( fullstackpython.com ):

If WSGI is the standard for synchronous Python apps then ASGI is the standard for synchronous and asynchronous Python apps . ASGI is suitable for all applications using WSGI due to its backward compatibility mechanism.

Okay enough, we continue to find out what utilities FastAPI also provides.

FastAPI Docs

Due to being based on OpenAI, which was formerly known as Swagger, FastAPI provides doc with easy-to-see and easy-to-use interface. Illustration:

When enabling the doc with the local url http://0.0.0.0:8000/docs .

1 other FastAPI interface docs http://0.0.0.0:8000/redoc .

Performance

You can test the performance of web frameworks on this page ( https://www.techempower.com/benchmarks/ )

Optional Depencies

Since FastAPI is based on Pydantic and Starlette, it’s okay to have additional support for some additional libraries:

Pydantic:

  • ujson : JSON “parsing” is faster.
  • email_validator : validate email.

Starlette:

  • requests : when you want to make a request, use TestClient .
  • aiofiles : when you want to use FileResponse or StaticFile .
  • jinja2 : if you want to use the default config templates.
  • python-multipart : supports “parsing” with request.form ().
  • itsdangerous : SessionMiddleware support.
  • graphene : GraphQL support.

FastAPI:

  • uvicorn : ASGI server caters to your application.
  • orjson : if you want to use ORJSONResponse .

If you want to use all of the above libraries, you just need to use one simple command.

Basic instructions

Create a simple API

Basically, the code is as easy as eating candy, you create a main.py file.

Then run this line of code to run the app

P / S: If you do it in development environment can add --reload to automatically restart after code change.

Then go to check the results of the broadcast http://127.0.0.1:8000/docs .

Click Try it out -> Execute -> API returns the response.

This API interface is based on OpenAPI. On that side there is a concept to define API called “Schema”. If you are curious, please visit this link http://127.0.0.1:8000/openapi.json .

Generally speaking, you only need 6 steps to create an API

  • Step 1: import fastapi
  • Step 2: Create an instance of class FastAPI
  • Step 3: create path, starting from /
  • Step 4: declare HTTP method: post, get, put, delete or options, head, patch, trace
  • Step 5: function declaration
  • Step 6: Return content with format dict, list, str, int, …

Path Parameters

You can pass the param over the path.

The variable item_id on the path will pass to the read_item function with the same param named item_id . Test http://127.0.0.1:8000/items/foo .

Path parameters with types

You can also declare the format of the param to return when passing a well-formatted variable that will return a value.

Data validation

If the format is not correct, a message is returned. All validated data is based on Pydantic.

Order

If you have declared duplicate paths like this:

Remember to order /users/me first and then /users/{user_id} later, otherwise if /users/{user_id} first, you will think that “user_id” gets the value me .

Path in path

FastAPI supports declaring the path in the API path thanks to based Starlette.

Query Parameters

If you pass the param as key-value, then in FastAPI there is support called “query” parameters.

Check it at the link http://127.0.0.1:8000/items/?skip=0&limit=10 :

If you notice that the skip and limit are formatted string as a path, but once passed to the function, they will be converted from string to int.

Optional parameters

In addition, FastAPI provides a way to declare optional query parameters, the default is None.

As you can see above, param passed in the path is item_id , but in the function, param is also q . FastAPI only uses str to determine the param format, and Optional is not used FastAPI, only checks the error if it occurs.

You can test with the following link.

Query parameter type conversion

Change the default value by passing the value on the path.

In this case

Multiple path and query parameters

With nested paths, FastAPI knows which param with which param based on param name.

Required query parameters

Simply fill in the missing param on the path will error

As shown below, I just pass the value of item_id and the value of needy should not generate an error.

Request Body

  • Request body: the user sends the request from the browser to the API.
  • Response body: Based on the request, APi returns a response to the user.

To declare the format of the request body, you need to use Pydantic models. P / S: prompted when sending a request to use the POST method, if you use the GET method, you will be exposed information on the URL => not high security.

Pydantic Models

Example of an instance of Item class.

Since the description and tax have the value None, you may not need to add them.

Based on the import of the Pydantic module, FastAPI supports:

  • Read request body as Json.
  • Convert variable format.
  • Validate data
  • Declare the default format of the request body, the Item class above is an example.
  • Gen JSON Schema for your model
  • Schema will be genetically transformed into UI of OpenAI doc.

Use model

In the create_item function, you can customize the Item class variables, as simple as calculating the taxable fee by calculating the sum of item.price and item.tax as shown below.

Request body + path parameters

FastAPI supports declaring URL parameters and request body at the same time, the framework will know which parameters pass from the path and which parameters are taken from the request.

P / S: Similar to above, you can add URL parameter, query parameter and request body at the same time.

Query Parameters and String Validations

In the previous part, we already know the concept of query parameter, it’s okay to have one type of param. This parameter has an attribute of Optional , but the length is limited to no more than 50 characters. So FastAPI provides Query class.

The statement q: Optional[str] = Query(None) is similar to q: Optional[str] = None but Query provides other parameters like max_leht, min_leht, regex, … You can increase the character limit to 250 like this just changing the parameter value. (Default of max_lenght is 50)

Query parameter list / multiple values

In addition to string and integer formats, FastAPI also supports List type.

Response body that the API returns.

The API is also updated as well.

P / S: You can also replace List[str] to list like this.

Query has a few more parameters, but not too important, you can go to the FastAPI doc to find out details.

The params that Query provides:

Metadata

  • alias : other name of param
  • title : metadata named param
  • description : metadata introduces param
  • deprecated : when you are bored of any param, add it to let the user know that you are no longer using that param

Validation for string:

  • min_lenght
  • max_lenght
  • regex

Path Parameters and Numeric Validations

Query parameters have a Query class to declare metadata and validations, Path parameters have a Pass class with a similar mechanism.

Add title metadata for path param item_id :

Number validations: greater than or equal

We can not only validate strings, but also numbers.

With param ge=1 of the Path class, item_id must be a number greater than or equal to 1

Number validations: greater than and less than or equal

Similar to le=100 , item_id must be a number less than or equal to 100.

P / S: Number validations not only supports type integer, but also support for type float.

  • gt : > gt >
  • ge : ge
  • lt : < lt <
  • le : le

Body

Multiple Parameters

Simply, FastAPI supports creating formats for the request body, you can use not only 1 but the N Pydantic model as in the example below, I declare 2 Item classes and User classes, respectively, 2 Pydantic models.

Singular values ​​in body

You can also add define a body for only 1 value without declaring the class, for example here I add an importance param with type int and also a key located in json body, so when you post data, you must also declare values ​​for importance .

Multiple body params and query

Simply put, it combines multiple body param with the query param.

Field

To validate data or add metadata in a class say Item for example, you need to import the Field operation function from the pydantic module.

As the above code, param description has metadata title, length does not exceed 300 words, or as param price not be less than 0 and has metadata as description.

Nested Models

In addition to the types int, float, and str, you can also add a list or set type as shown below.

With the above declaration, when you pass the param is 1 list, but with the above declaration, this list will not determine the format of each element in the list. That’s okay because Python has a List module that supports you to declare a param as a list that determines the format of each element.

Similar to List , you can add Set .

In addition, normal types such as str, int, float, … FastAPI also supports more complex and diverse formats, assuming the HttpUrl format inherits from str . For more information please check this link ( https://pydantic-docs.helpmanual.io/usage/types/ ).

  • Next, I will introduce you how to declare a model nested in another model.

Let’s say I have 2 classes Images and Item.

I want the Images class to be in Item class like this.

You just need to add 1 line of code to the Item class. Easy!

You can also customize the format of Pydantic models to be list or set, for example.

And this is the result.

In theory you could repeat the nested models as follows. The Image class is in the Item class, while the Item class is in the Offer class.

Conclude

Since FastAPI is a new API framework with a lot of features, I split it up into several parts (basically due to not being patient enough to write). Here I will only list the important features that are used a lot first and then advance in the next sections. You can also check it directly on the doc by fastapi. Link refer here:

Share the news now

Source : Viblo