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:
1 |
pip install fastapi |
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:
- Create a virtual environment: python3 -m venv venv
- Activate the virtual environment: source venv/bin/activate
- Install the required packages: pip install fastapi pymysql
- Create a new file app.py and paste the code from the previous example.
- Start the development server: uvicorn app:app –reload
- Create database mydb and table Items with the following SQL commands:
1 2 3 |
CREATE DATABASE mydb; USE mydb; CREATE TABLE items (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255)); |
Test the API with a REST client like Postman or cURL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Get all items GET http://localhost:8000/item # Get item by id GET http://localhost:8000/item/1 # Create a new item POST http://localhost:8000/item Body: { "name": "item name" } # Update item by id PUT http://localhost:8000/item/1 Body: { "name": "updated item name" } # Delete item by id DELETE http://localhost:8000/item/1 |
This is the complete example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
from fastapi import FastAPI, Depends from pydantic import BaseModel import pymysql app = FastAPI() def get_db(): conn = pymysql.connect( host='localhost', user='root', password='', database='mydb' ) return conn class Item(BaseModel): id: int name: str @app.get("/item/{item_id}") def read_item(item_id: int, db: pymysql.Connection = Depends(get_db)): with db.cursor() as cursor: cursor.execute(f'SELECT * FROM items WHERE id={item_id}') item = cursor.fetchone() return {"item": item} @app.post("/item/") def create_item(item: Item, db: pymysql.Connection = Depends(get_db)): with db.cursor() as cursor: cursor.execute(f'INSERT INTO items (name) VALUES("{item.name}")') db.commit() return {"item": item} @app.put("/item/{item_id}") def update_item(item_id: int, item: Item, db: pymysql.Connection = Depends(get_db)): with db.cursor() as cursor: cursor.execute(f'UPDATE items SET name="{item.name}" WHERE id={item_id}') db.commit() return {"item": item} @app.delete("/item/{item_id}") def delete_item(item_id: int, db: pymysql.Connection = Depends(get_db)): with db.cursor() as cursor: cursor.execute(f'DELETE FROM items WHERE id={item_id}') db.commit() return {"result": "item deleted"} |
To run the code you can open terminal window in the same directory as the code file and run the following command:
1 |
uvicorn main:app --reload |
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
- Is Python Good for GUI Apps
- Is Python Good for Ethical Hacking
- Python Best Libraries for Web Development
- Top 10 Python REST API Frameworks
- How to Build REST API with Flask
This will be the result.