การดำเนินการ GET

FastAPI เบื้องต้น

Matt Eckerle

Software and Data Engineering Leader

ทบทวนการดำเนินการ GET

โปรโตคอล HTTP - มีการดำเนินการหลายประเภท

  • GET เป็นประเภทที่ใช้บ่อยที่สุด

ตัวอย่าง: https://www.google.com:80/search?q=fastapi

ส่วนประกอบหลักของคำขอ GET:

  • Host เช่น www.google.com
  • Port เช่น 80 (ค่าเริ่มต้น)
  • Path เช่น /search
  • Query String เช่น ?q=fastapi
FastAPI เบื้องต้น

การดำเนินการ GET ด้วย FastAPI

แอปพลิเคชัน FastAPI ที่ง่ายที่สุด:

from fastapi import FastAPI

# Instantiate app app = FastAPI()
# Handle get requests to root @app.get("/") def root(): return {"message": "Hello World"}
1 https://fastapi.tiangolo.com/tutorial/first-steps/
FastAPI เบื้องต้น

การใช้งาน cURL

ตัวเลือกหลักของ cURL:

$ 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

ตัวอย่างการใช้งาน:

$ curl http://localhost:8000
{"message":"Hello World"}
FastAPI เบื้องต้น

Query Parameters

Endpoint ใหม่:

  • Path: "/hello"
  • Query parameter: "name"
    • ค่าเริ่มต้น: "Alan"
@app.get("/hello")
def hello(name: str = "Alan"):
    return {"message": f"Hello {name}"}

ไม่ระบุชื่อในคำขอ: เทอร์มินัลแสดงคำขอ curl โดยไม่ระบุชื่อ ข้อความตอบกลับคือ "Hello Alan"

ระบุชื่อในคำขอ: เทอร์มินัลแสดงคำขอ curl โดยระบุชื่อ ข้อความตอบกลับคือ "Hello Steve"

FastAPI เบื้องต้น

มาฝึกกันเลย!

FastAPI เบื้องต้น

Preparing Video For Download...