Skip to content

huytranvan2010/FastAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI

API - Application pesornal iterface (giao diện ứng dụng người dùng).

Bình thường xây dựng model nhận diện khuôn mặt chẳng hạn, không thể bảo người dùng (kiểm tra) cài cắm môi trường, chạy câu lệnh để test thử. Lúc này chúng ta cần API.

FastAPI có hỗ trợ:

  • Đồng bộ Async
  • Validate data (bên Flask phải thực hiện thủ công), dùng pydantic
  • Tự sinh documents (hỗ trợ bên front end)

Cài đặt

pip install fastapi
pip install uvicorn
from typing import Optional
from fastapi import FastAPI

app = FastAPI()

# # ko dùng asyns
# @app.get("/")
# def read_root():
#     return {"Hello": "World"}

# @app.get("/items/{item_id}")
# def read_item(item_id: int, q: Optional[str] = None):
#     return {"item_id": item_id, "q": q}

# dùng async
@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

Chạy

uvicorn main:app --reload

The command uvicorn main:app refers to:

  • main: file main.py
  • app: object được tạo trong file main.py ở dòng app = FastAPI()
  • --reload: server restart lại khi thay đổi code (khi development thôi)

Chạy thử http://127.0.0.1:8000/items/5?q=somequery

Như vậy chúng ta đã tạo API:

  • Nhận HTTP requests trong đường dẫn //items/{item_id}
  • Cả 2 paths đều lấu GET operations (HTTP methods)
  • Path /item/{item_id} có parameter item_id nhận vào int
  • Path /item/{item_id} có optional str query parameter

Nếu muốn xem docs chỉ cần vào http://127.0.0.1:8000/docs. Ở trong này có thể tìm hiểu được các lấy request, chạy thử luôn ví dụ, rất dễ hiểu.

Tài liệu tham khảo

https://fastapi.tiangolo.com/

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages