How to Build Python REST API with FastAPI

In this lesson i want to show you How to Build Python REST API with FastAPI.


What is FastAPI ?

FastAPI is modern and high performance web framework for building APIs with Python 3.7+ based on standard Python type hints. it is built on top of Starlette for the web parts and Pydantic for the data parts.

FastAPI has number of advantages compared to other Python web frameworks, including

Fast to code: decrease the amount of redundant code, increase productivity. -Fewer bugs: reduce about 40% of human (developer) induced errors.

Easy to maintain: FastAPI makes it easier to keep the code up to date.

Fast to run: FastAPI is very high performance on par with NodeJS and Go (thanks to Pydantic and async support). one of the fastest Python frameworks available. 

FastAPI also integrates with other popular libraries such as Django ORM, Tortoise ORM and asyncio. you can install FastAPI by using pip with the following command in your terminal or command prompt:



This is an example of building FastAPI REST API with MySQL database, these are the steps to build FastAPI REST API with a MySQL database:

  1. Create a virtual environment: python3 -m venv venv
  2. Activate the virtual environment: source venv/bin/activate
  3. Install the required packages: pip install fastapi pymysql
  4. Create a new file and paste the code from the previous example.
  5. Start the development server: uvicorn app:app –reload
  6. Create database mydb and table Items with the following SQL commands:



Test the API with a REST client like Postman or cURL



This is the complete example 



To run the code you can open terminal window in the same directory as the code file and run the following command:

Here, main is the name of the file containing the code, and app is the instance of the FastAPI application. The –reload flag ensures that the server automatically reloads when changes are made to the code.




Lean More on Python



This will be the result.

How to Build Python REST API with FastAPI
How to Build Python REST API with FastAPI


Leave a Comment