GET 操作

FastAPI 入门

Matt Eckerle

Software and Data Engineering Leader

GET 操作回顾

HTTP 协议:多种操作类型

  • GET 最常见

示例:https://www.google.com:80/search?q=fastapi

GET 请求的关键部分:

  • 主机,如 www.google.com
  • 端口,如 80(默认)
  • 路径,如 /search
  • 查询字符串,如 ?q=fastapi
FastAPI 入门

FastAPI 的 GET 操作

最简单的 FastAPI 应用:

from fastapi import FastAPI

# 实例化应用 app = FastAPI()
# 处理根路径的 GET 请求 @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 入门

查询参数

新增端点:

  • 路径:"/hello"
  • 查询参数:"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...