FastAPI(2)快速入门
1、安装FastAPI安装fastapi和unicorn模块,unicorn可以作为服务器pip install fastapi -i https://pypi.tuna.tsinghua.edu.cn/simplepip install unicorn -i https://pypi.tuna.tsinghua.edu.cn/simple2、启动一个最简单的例子# filename: main.
·
1、安装FastAPI
- 安装
fastapi
和unicorn
模块,unicorn可以作为服务器
pip install fastapi -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install unicorn -i https://pypi.tuna.tsinghua.edu.cn/simple
2、启动一个最简单的例子
# filename: main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello, world!"}
- 命令行中使用命令
unicorn main:app --reload
启动服务,命令讲解main
main.py文件,表示main模块app
main.py中创建的app对象--reload
开发时使用,可以修改源码后立即生效
- 浏览器中访问:
http://127.0.0.1:8000
可以查看到如下内容
3、两种查看接口文档的方法
-
查看交互式API文档:
http://127.0.0.1:8000/docs
-
第二种:
http://127.0.0.1:8000/redoc
4、OpenAPI
FastAPI使用API的OpenAPI
标准为所有API生成schema
schema
- 是对事物的一种定义或描述
- 不是具体的实现代码,只是抽象的描述
- 大概是这样的
from pydantic import BaseModel, Schema class Item(BaseModel): name: str description: str = Schema(None, title="the description of the item", max_length=30) ... ...
API Schema
- OpenAPI是一种规范,它规定如何定义API Schema
- 定义OpenAPI Schema将包括API路径,以及它们可能使用的参数等等
- 比如: 这个API的作用是什么,哪些是必传的参数,请求方法是什么
Data Schema(??)
- 指的是某些数据,比如JSON的结构
- 它可以表示JSON的属性及其具有的数据类型
- 比如: 某个属性的数据类型是什么,有没有默认值,是不是必填,作用是什么
JSON Schema
- OpenAPI会为API定义API Schema,一般会包括API发送和接收的数据的定义,比如:发送的数据类型、是否必填
- 这些定义会以JSON数据格式展示出来,所以称为:JSON Schema
原始的OpenAPI Schema
- 通过
http://127.0.0.1:8000/openapi.json
查看,原始的OpenAPI Schema只包含了所有的JSON数据结构的API描述
{ "openapi": "3.0.2", "info": { "title": "FastAPI", "version": "0.1.0" }, "paths": { "/": { "get": { "summary": "Root", "operationId": "root__get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {} } } } } } } } }
5、详解上面的那个例子
# FastAPI是一个为API提供所有功能的PYTHON类
# FastAPI直接从Starlette继承的类,可以通过FastAPI使用Starlette的功能
from fastapi import FastAPI
# app是FastAPI类的一个实例
# uvicorn启动时会用到这个app
app = FastAPI()
# 创建一个路径操作
@app.get("/")
async def root(): # 定义路径操作函数
# return: 函数返回内容
return {"message": "hello, world!"}
创建一个路径操作
- 路径:指的是URL从第一个
/
起的后半部分,也就是常说的path,也称为端点
路由
- 操作:就是请求方式,可以使用
POST
GET
PUT
DELETE
OPTIONS
HEAD
PATCH
TRACE
中的任意一种方式与每个路径进行通信 - 遵循RESTFul风格的话,一般:
POST
创建数据GET
获取数据PUT
更新数据DELETE
删除数据
- 定义一个路径操作的装饰器:
@app.get("/")
定义路径操作函数
- 该函数其实就是一个普通Python函数
- 每当FastAPI接收到一个使用
GET
方法访问路径/
的请求时,就会调用root()
函数 async
表示异步处理函数
更多推荐
所有评论(0)