Contents:

Learn Python for free: from a Telegram bot to a website under the guidance of an expert from Sber
Find out morePython is not known for its high execution speed, and for projects with intensive workloads, many developers prefer to use Go or Node.js. However, with the advent of FastAPI, the situation has changed: now it is possible to create fast, asynchronous and easily scalable web applications in Python. In this article, we will consider what exactly distinguishes FastAPI from other tools and demonstrate how you can develop a full-fledged API with automatic documentation generation from scratch.
Contents
- What is FastAPI
- What are the advantages of FastAPI
- Disadvantages of FastAPI
- Developing your own API using FastAPI
- Project overview
- What's next?
What is FastAPI
FastAPI is a modern framework for developing web applications and APIs in Python, which has gained popularity due to its simplicity and high speed. With just a few lines of code, you can set up a server that can accept requests, process them, and return results—whether that's database data, neural network responses, or calculation results.
FastAPI was developed in 2018 to address the shortcomings of traditional Python frameworks like Flask and Django. While these tools were good at building basic websites, they began to run into performance issues as request volumes increased and Python's asynchronous approach shifted.
This brand-new framework combines a number of key technologies to deliver exceptional speed and ease of use:
- Starlette is the core of the application and defines the process by which the server accepts and processes incoming requests. It is thanks to this that FastAPI can operate in asynchronous mode and handle high loads.
- Pydantic provides data verification, which is especially useful in situations where, for example, a user attempts to submit text instead of a numeric value. In such cases, the framework will immediately throw an error, preventing the entire application from crashing.
- Type annotations in Python help create clearer and safer code: you simply indicate what data you expect to receive, and FastAPI automatically checks it and adds all the necessary information to the documentation.
FastAPI finds its application in situations that require fast request processing, covering both small services and large-scale platforms. Python developers use it to create the server side of web applications, while DevOps specialists and integration engineers use it to create microservices and interconnect various systems. Machine learning professionals also use FastAPI to deploy models and make them accessible via APIs.
The framework is used to develop chatbots, as well as to create IoT devices that require a rapid response to incoming data.
What's so great about FastAPI
The main advantages of FastAPI are its exceptional speed, reliability, and the ability to automatically generate documentation.
Efficiency. Comparable to languages such as Node.js and Go, thanks to its asynchronous architecture: the framework does not linger waiting for one operation to complete before moving on to the next. It is capable of handling multiple requests simultaneously, or rather, switching between them so quickly that it is practically unnoticeable.
Independent tests, including the Sharkbench test, have confirmed the effectiveness of the framework. Applications developed with FastAPI demonstrated some of the best speed results among all Python frameworks. This allows for significant savings on server resources, which is especially important for projects that expect high traffic.
Typing and Validation. Using FastAPI, you'll notice that the amount of code you need to write is significantly reduced thanks to type annotations: you specify data types, and the framework automatically checks them.
Here, for example, is a basic function that adds two numbers and contains no annotations:
In the example above, Python has no information about the types of the variables a and b. Consequently, the function will either sum numbers or concatenate strings, depending on the data passed. If the types are incorrect, the program will not display errors, but the final result may be incorrect.
Here is an example of using FastAPI, where the typing is specified directly in the function arguments:
In this case, a: int and b: int are parameters that FastAPI automatically validates, ensuring that the incoming request contains numeric values. The request format is represented as follows:
Response:
If a value is passed instead of a number, for example, a=five, FastAPI will immediately generate an error, indicating that the entered data is invalid.
Interactive documentation. FastAPI automatically creates documentation, forming a page that displays all available endpoints (addresses for requests), parameters, and possible responses.
When the application starts, FastAPI automatically creates two special routes - usually /docs and /redoc. If you access these pages through a browser, you'll find an interactive interface that allows you to select any API method, view the data it accepts, and test it directly in the browser.


Programmers, testers, and analysts can monitor changes in the API structure as a result of software updates, monitor the addition of new fields, identify errors, and check server responses.
FastAPI Disadvantages
FastAPI is an excellent and high-speed framework, but it is not without certain drawbacks.
Asynchronous approach. Asynchronous operation is one of the factors contributing to the high speed of FastAPI, but it requires care. If you accidentally use synchronous code inside an asynchronous function, the server will wait for this operation to complete, which negates all the benefits of asynchrony. Therefore, developing and debugging applications on FastAPI can be a more challenging task, especially for those just starting with this technology.
Performance is not always great. FastAPI does outperform Flask in situations where it is necessary to handle a large number of requests simultaneously, especially under asynchronous execution. However, if the application handles simple tasks one by one, the difference in speed becomes barely noticeable. In some cases, Flask or Django may even perform better because they have fewer built-in checks, which reduces the time it takes to process each individual request.
The FastAPI ecosystem is less developed. While Django is a full-fledged framework for building web applications, FastAPI is more like a set of components from which the developer must assemble everything needed. There are no built-in solutions for administration, background tasks, or user management—the developer must implement registration, authorization, and email confirmation algorithms themselves.
This method offers freedom of choice and adaptability, but requires significant experience and time. FastAPI is ideal for those who prefer to determine on their own which tools to use, instead of relying on an existing architecture.

Read also:
Creating the perfect Web API: recommendations and common mistakes to avoid
Developing a Web API requires a careful approach and knowledge of many nuances. To create a truly effective interface, it's important to consider several key aspects and be alert to common mistakes.
First and foremost, it's crucial to properly design the API structure. It's essential to clearly define what data will be available and how users will be able to request it. Standard practices, such as using RESTful principles, can significantly simplify the process of developing and interacting with the API. It's also important to consider that different clients may have different requirements, so it's worth considering the flexibility and extensibility of the interface.
When designing, it's important to maintain consistency in endpoint names and request types. This not only makes things easier for developers but also makes the API more intuitive for users. Furthermore, proper use of HTTP status codes allows for clearer communication about the request result, improving the overall experience.
API security is equally important. Authentication and authorization methods must be implemented to protect data and prevent unauthorized access. Using tokens and data encryption will help increase the security of your API.
Documentation is also a good place to start. Well-written and clear documentation will significantly simplify the integration process for developers using your API. It is important to describe in detail all the interface capabilities, request and response examples, and also indicate possible errors and how to resolve them.
Finally, don't forget about testing. Regularly checking the functionality and performance of your API will help identify flaws early and improve its quality.
By studying the above recommendations and avoiding common mistakes, you can create a reliable and user-friendly web API that will meet the needs of your users.
Developing Your Own API Using FastAPI
We will develop a full-fledged API that will include database support, as well as functions for authorization and authentication of users. Don't worry if you don't have experience working with databases—we will use a simulated one. However, it is important that you have basic knowledge of Python version 3.8 or higher and an understanding of the basics of working with the terminal, otherwise you will have a hard time mastering the material.
First, you need to create a virtual environment. A virtual environment is an isolated environment for working with Python, which is separate from the main environment of your operating system. This is necessary to avoid conflicts between packages and the system. Enter the following command in the terminal:
Or:
You have created a directory called fastapi_project and installed the virtual environment. Provided that all steps were followed correctly, the fastapi_project folder should contain the bin, include, lib, lib64 directories, as well as a file called pyvenv.cfg.
Now you need to activate the environment. If you are using Linux or Mac:
On Windows:
Provided that you have completed all the steps, the name (fastapi_project) should be displayed before the prompt in the terminal. This indicates that your environment is successfully active.

Install FastAPI:
Now that the project is successfully configured, you can proceed to completing tasks.

Read also:
Installing PIP for Python: A Step-by-Step Guide and Key Commands
PIP, a package manager for Python, allows you to easily install and manage third-party libraries. To get started with PIP, you need to install it. Let's see how to do this.
1. Check if Python is installed. Open a terminal or command prompt and enter the command:
«`
python —version
«`
or
«`
python3 —version
«`
If Python is installed, you will see its version. Otherwise, you need to download and install Python from the official website first.
2. If Python is already installed, PIP may be installed along with it. To do this, run the following command:
«`
python -m ensurepip
«`
or
«`
python3 -m ensurepip
«`
3. If you already have PIP but want to upgrade to the latest version, use the command:
«`
python -m pip install —upgrade pip
«`
or
«`
python3 -m pip install —upgrade pip
«`
Now that PIP is installed, you can start using it to install libraries. Here are some basic commands you might need:
— To install a package, run the command:
«`
pip install package_name
«`
— To uninstall a package, use:
«`
pip uninstall package_name
«`
— To list all installed packages, run:
«`
pip list
«`
— To get information about a specific package, use:
«`
pip show package_name
«`
These commands will help you effectively manage Python libraries through PIP.
Let's develop our first API. To do this, create a main.py file in the fastapi_project directory and paste the following code into it:
To start the server, make sure you are in the fastapi_project directory:
Launch your browser and enter the address http://127.0.0.1:8000. The message {«message»: «Hello World»} will appear on the screen.

You can view the documentation by going to the following address: http://127.0.0.1:8000/docs. After that, select GET /, click the "Try it out" button, and then run the command to see the result.

The answer will also be visible in the terminal.

To terminate the server, use the key combination Ctrl + C. Restarting the server after editing the code is not required, since FastAPI has an automatic loading function changes. If your text editor doesn't have an autosave feature, be sure to save the file after each change, otherwise your code changes won't be reflected on the server.
Endpoints are the addresses in your API that clients use to make requests. We already used the automatically created /docs endpoint when we were looking at the documentation. Now let's create our own. To do this, create a file called endpoints.py in the fastapi_project directory:
Let's edit the main.py file by importing the register_endpoints function and calling it.
Let's check that everything is working correctly. Open the link http://127.0.0.1:8000/items/5 - in response, you should see {«item_id»: 5}.

When attempting to access the address http://127.0.0.1:8000/items/abc, FastAPI will generate an error because it expects a number to be passed in this place.

A structure represented as {«item_id»: 5} is commonly called a path parameter. It is a URL element that can change. In this example, any integer can be inserted after the items/ fragment.
Let's introduce a query parameter—this is information that is passed through the URL after the ? symbol. For example, the address http://127.0.0.1:8000/items/5?q=hello passes the q parameter with the value hello. Using query parameters allows you to conveniently pass additional information, such as search queries. Now let's change the items/ endpoint:
Now, by following the link http://127.0.0.1:8000/items/5?q=hello, we will get the following response: {«item_id»: 5, «q»: «hello»}.

At http://127.0.0.1:8000/items/5 you can see the following response: {«item_id»: 5, «q»: null}.

In some cases, it is necessary to set restrictions on the values that the user can pass via a URL. For example, suppose we create a models/ endpoint with a {model} parameter that is allowed to accept only two values: a and b. The built-in Enum module is ideal for this purpose, as it is designed for creating enumerations of constants. In the endpoints.py file, add an import for Enum and create a class to store these values:
At the end of the register_endpoints function, we'll implement the new endpoint, taking into account the correct indentation:
Go to http://127.0.0.1:8000/models/a, and you'll get a response in the format {«model»: «a»}. The same thing happens if you go to http://127.0.0.1:8000/models/b. However, if you try to access http://127.0.0.1:8000/models/c, FastAPI will return an error because c is not included in the list of valid values specified in Model.

Media
We'll implement two new endpoints for users: one will be static and the other dynamic.
It's important to maintain the order to avoid confusion on the part of FastAPI. Thus, at the address http://127.0.0.1:8000/users/me we will receive a response in the form {«user_id»: «me»}.
If we access the address, for example, http://127.0.0.1:8000/users/igor, we will receive the following result in response: {«user_id»: «igor»}.
We'll introduce the ability to receive data from the user through the request body. This body will function as a form that the user fills out and submits to the server.
In our project, we will use Pydantic, a library designed to verify the correctness of data format (for example, to make sure that a number is actually a number and not text). If invalid data is detected, FastAPI will automatically generate an error. In addition, we will implement a validation mechanism that will block products with an excessively high price.
Please update the imports in the endpoints.py file.
Introduce a class that describes the data structure:
Add a new endpoint to the end of the register_endpoints list:
Go to http://127.0.0.1:8000/docs, then find the POST /items/ endpoint. Click the «Try it out» button and send the request using the JSON format. This data format resembles a dictionary in Python:
The response to your request will be data in the format: {«name»: «apple», «price»: 1.5, «description»: «A juicy apple»}. However, if you try to send data in the form {«name»: «apple», «price»: «abc»}, the FastAPI system will return a 422 error, since the value for the price field must be a number. If you send {«name»: «apple», «price»: 150}, a 400 error with the message "Too expensive" will occur because the price exceeds the limit of 100.
Authentication answers the question of your identity, while authorization determines your rights and capabilities. As part of our security system, we will implement two protection methods: an API key, which will be presented in the request header, and HTTP Basic, which requires a username and password. Let's start with the API key integration. To do this, create an auth.py file in the fastapi_project directory:
In the endpoints.py file, you need to update the imported modules.
Please replace the current get.items/ endpoint with the endpoint that uses the API key in the endpoints.py file:
In the /docs section, for the GET /items/{item_id} request, you must enter the secret code in the Authorize field. Access to the authorization form is provided through the green button with the image of a lock that appears on the right.

Run a test using item_id equal to 5 - as a result, you will receive a response in format {«item_id»: 5, «q»: null}. If you enter an incorrect key, the system will return a 401 error.

We will implement the authorization process. You need to update the imports in the auth.py file:
Include the username and password verification procedure for both the standard user and the administrator at the end of the document.
In the endpoints.py file, you need to make changes to the imported modules from auth.py.
Update the endpoint with a predefined user:
Implement the administrative endpoint:
Let's check that everything is functioning correctly. Go to /docs. For the GET /users/me request, enter your username in the user field and your password in the pass field in the Authorize → HTTP Basic section. As a result, you should receive a response in the format {«user_id»:

Try making a GET request /admin/ via the function «Try it out» → «Execute» without prior authentication. As a result, you will receive a 403 error with the notification "For administrators only."

When you enter the login admin and password pass, the system will return a response in the format: {«message»: «Welcome, admin»}.

In the catalog fastapi_project, you need to create a file named database.py.
In the endpoints.py file, you need to make changes by adding the appropriate imports.
In the register_endpoints function, you should update the previous post/items/ endpoint with the new one.
Send a POST request to /items in the /docs section.

The product will be saved in the db.json file, which was created automatically.
To access all added products, you need to add another endpoint in the endpoints.py file:
Go to the /docs section and make a GET request to /items/. As a result, you will get a list of products, for example, [{«name»: «apple», «price»: 1.5, «description»: «A juicy apple»}].


Read also:
A database is an organized collection of information designed to store, manage, and process data. It serves as the foundation for systems that require structured access to various types of information. The primary purpose of a database is to simplify the storage and retrieval of data, as well as to ensure its integrity and security.
Databases are essential for a variety of applications, from corporate accounting to website storage. They allow users and applications to quickly find the data they need, analyze it, and support interaction between different systems. In today's rapidly growing data environment, databases are becoming increasingly important for effective information management.

Project Overview
Project Completed! Your fastapi_project folder should now contain five files: main.py, endpoints.py, auth.py, database.py, and db.json. If you encounter any issues, review your code for errors.
main.py:
endpoints.py:
auth.py:
database.py:
The db.json file will contain all the information you saved using POST requests. In this example, it will only contain one product:
Verify that the final versions of the documents have been saved and that the commands in the terminal are entered correctly.
What's next?
For a more in-depth understanding of FastAPI, check out its official documentation. It covers all its features, including asynchronous capabilities and integrations. The documentation includes tutorials, code samples, and best practice recommendations. Although the primary language is English, automatic translation into Russian is provided. We recommend starting with the "Tutorial - User Guide" section. The documentation is regularly updated, ensuring that the information is up-to-date. It is an ideal resource for learning complex aspects.
As part of our project, we created a mock database. However, this is not suitable for real-world use. To understand the correct approach, it is worth familiarizing yourself with relational and non-relational databases.
Practical projects require testing. Python has several libraries designed for this purpose. One of the most well-known is Pytest.
To make a project available to other users, it must be deployed correctly. Docker is currently widely used in the industry. The documentation has a separate section that describes in detail how to use it to deploy an application to FastAPI.
Learn more exciting information about programming in our Telegram channel. Join us!
Read also:
- Telegram Bot API: A Guide for Bot Developers
- Creating the Perfect Web API: Best Practices and Common Mistakes in Development
- REST API is an architectural style used to create web services. It is based on the principles of REST (Representational State Transfer), which allows applications to communicate with each other via the HTTP protocol. The basic idea is to use standard HTTP methods such as GET, POST, PUT, and DELETE to perform operations on resources represented in various data formats, most commonly JSON or XML.
A REST API begins with a client sending a request to a server, which processes the request and returns an appropriate response. Each resource in the system has a unique identifier, usually represented as a URL. This allows the client to specify exactly which resource they want to interact with.
REST APIs are easily scalable and offer the ability to use caching to optimize performance. Importantly, they don't require maintaining state between requests, making them lightweight and efficient for distributed systems. Thus, REST APIs have become a popular choice for developing modern web applications and mobile services.
