FastAPI 是一个高性能 Web 框架,也是一个Python包,用于构建 API,适合利用极少的代码搭建服务器后端,实现前后端分离。
RESTful API 就是REST风格的API。现在终端平台多样,移动、平板、PC等许多媒介向服务端发送请求后,如果不适用RESTful API,需要为每个平台的数据请求定义相应的返回格式,以适应前端显示。但是RESTful API 要求前端以一种预定义的语法格式发送请求,那么服务端就只需要定义一个统一的响应接口,不必像之前那样解析各色各式的请求。
常见的API方法
需要使用的Python包:fastapi和uvicorn。
代码:
apiCore.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import uvicorn from fastapi import FastAPI, Query, Form, APIRouter, File, UploadFile from fastapi.middleware.cors import CORSMiddleware import time app = FastAPI( title="demo", docs_url='/api/v1/docs', redoc_url='/api/v1/redoc', openapi_url='/api/v1/openapi.json' ) router = APIRouter() @router.get('/paper') async def fetch_paper( num: int = Query(..., description='returned paper num', example='10') ): start = time.time() print(num) return {'time': time.time() - start, 'data': num} @router.post('/add_paper') async def add_paper( name: str = Form(..., description='paper name', example='Attention is all you need'), info: str = Form(..., description='paper info', example='NIPS 2017') ): start = time.time() print(name, info) return {'time': time.time() - start} @router.put('/update_paper') async def update_paper( p_id: str = Form(..., description='paper id', example='1234'), ): start = time.time() print(p_id) return {'time': time.time() - start} @router.delete('/delete_paper') async def delete_paper( p_id: str = Query(..., description='paper is', example='1234') ): start = time.time() print(p_id) return {'time': time.time() - start} app.include_router(router) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) if __name__ == '__main__': uvicorn.run(app=app, host="127.0.0.1", port=8000, workers=1) |
控制台启动(在局域网下):
1 |
uvicorn apiCore:app --reload --port 9918 --host 0.0.0.0 |
更多:
您好,fastapi上传文件解析,提示422 Unprocessable Entity,应该怎能处理?非常期望能得到您的帮忙!
这个是你前端api的值和后端接收的参数类型不匹配