0%

Building a FastAPI RESTful API from Scratch

1.​Introduction to FastAPI​

Why FastAPI?

  • High Performance:
    FastAPI is built on Starlette and Pydantic, supports async features, and its performance is close to Node.js and Go, far surpassing traditional frameworks like Flask and Django.

  • Asynchronous Support:
    Native support for async/await, suitable for high-concurrency scenarios.

  • Automatic Documentation:
    With simple annotations, FastAPI automatically generates interactive API docs (Swagger UI and ReDoc), making development and testing much easier.

2.​Project Setup

1
pip install fastapi uvicorn

3.​Creating Your First API​

1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
return {"message": "Hello World"}

4.​​Adding Routes and Pydantic Models

1
2
3
4
5
6
7
8
9
 from pydantic import BaseModel

class Item(BaseModel):
name: str
price: float

@app.post("/items/")
async def create_item(item: Item):
return {"item": item}

5.A Simple FastAPI Application Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
app = FastAPI()


class Item(BaseModel):
name: str
price: float

@app.get("/")
async def root():
return {"message": "Hello World"}

@app.post("/items/")
async def create_item(item: Item):
return f'{item.name} {item.price}'

if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)

The following image shows the interactive API documentation (Swagger UI) automatically generated by FastAPI, where developers can directly test the endpoints.