fastapi之helloworld

时间:2021-07-14 10:14:54   收藏:0   阅读:23

简介

以下简介来自官网描述:

FastAPI是一个用于构建API的现代、快速(高性能)的web框架,使用Python3.6+并基于标准的Python类型提示。

关键特性:

安装

pip install fastapi

fastapi不像django那样自带web服务器,所以还需要安装uvicorn或者hypercorn

pip install uvicorn

code01: hello.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "world"}

@app.get("/item/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

运行

uvicorn hello:app --reload

命令说明:

打开浏览器访问:127.0.0.1:8000,将显示:{"Hello":"world"}
技术分享图片
浏览器访问:127.0.0.1:8000/item/1,将显示:{"item_id":1,"q":null}

浏览器访问:127.0.0.1:8000/item/1?q=hello,将显示:{"item_id":1,"q":"hello"}

交互式API文档

浏览器访问:127.0.0.1:8000/docs,将会看到由 Swagger UI自动生成的交互式API文档
技术分享图片

或者访问:127.0.0.1:8000/redoc,会看到由redoc自动生成的文档。
技术分享图片

code02: main.py (官方文档中的代码)

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: Optional[bool] = None

@app.get("/")
def read_root():
    return {"Hello": "world"}

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

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}

多了一个put请求,可以在文档页调试这个接口测试。

原文:https://www.cnblogs.com/XY-Heruo/p/15009101.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!