Các thao tác GET

Nhập môn FastAPI

Matt Eckerle

Software and Data Engineering Leader

Ôn tập thao tác GET

Giao thức HTTP - nhiều loại thao tác

  • GET là phổ biến nhất

Ví dụ: https://www.google.com:80/search?q=fastapi

Các phần chính của một yêu cầu GET:

  • Host, ví dụ: www.google.com
  • Cổng (Port), ví dụ: 80 (mặc định)
  • Đường dẫn (Path), ví dụ: /search
  • Chuỗi truy vấn (Query String), ví dụ: ?q=fastapi
Nhập môn FastAPI

Thao tác GET trong FastAPI

Ứng dụng FastAPI tối giản:

from fastapi import FastAPI

# Khởi tạo app app = FastAPI()
# Xử lý GET tới root @app.get("/") def root(): return {"message": "Hello World"}
1 https://fastapi.tiangolo.com/tutorial/first-steps/
Nhập môn FastAPI

Dùng trình khách web cURL

Tùy chọn cURL chính:

$ curl -h
Usage: curl [options...] <url>
 -v, --verbose               Make the operation more talkative
 -H, --header <header/@file> Pass custom header(s) to server
 -d, --data <data>           HTTP POST data

Ví dụ dùng:

$ curl http://localhost:8000
{"message":"Hello World"}
Nhập môn FastAPI

Tham số truy vấn

Endpoint mới:

  • Path: "/hello"
  • Tham số truy vấn: "name"
    • Giá trị mặc định: "Alan"
@app.get("/hello")
def hello(name: str = "Alan"):
    return {"message": f"Hello {name}"}

Không có name trong yêu cầu: Cửa sổ terminal chạy curl không truyền name. Phản hồi: "Hello Alan."

Có name trong yêu cầu: Cửa sổ terminal chạy curl có truyền name. Phản hồi: "Hello Steve."

Nhập môn FastAPI

Hãy luyện tập!

Nhập môn FastAPI

Preparing Video For Download...