fastapi基础篇

简介: fastapi基础篇

简介

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

关键特性

快速:可与 NodeJS 和 Go 并肩的极高性能(归功于 Starlette 和 Pydantic)。最快的 Python web 框架之一。

高效编码:提高功能开发速度约 200% 至 300%。*

更少 bug:减少约 40% 的人为(开发者)导致错误。*

智能:极佳的编辑器支持。处处皆可自动补全,减少调试时间。

简单:设计的易于使用和学习,阅读文档的时间更短。

简短:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。

健壮:生产可用级别的代码。还有自动生成的交互式文档。

标准化:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为 Swagger) 和 JSON Schema。

环境搭建

安装

pip install fastapi[all]

基础文件

main.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
    return {"coleak"}
@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

使用上面的方式需要使用搭建时的fastapiproject运行配置才可以,或者直接使用下面的方式一样的

from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
async def root():
    """这里是首页"""
    return {"coleak"}
@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
if __name__ == '__main__':
    uvicorn.run(app)

test_main.http

# Test your FastAPI endpoints
GET http://127.0.0.1:8000/
Accept: application/json
###
GET http://127.0.0.1:8000/hello/User
Accept: application/json
###

自动文档

redoc
docs

基础使用

POST请求

# @app.post("/login")
# def login():
#     return {"message":"successful"}
@app.api_route("/login", methods=["GET", "POST"])
def login():
    return {"message": "successful"}

传递参数

@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
@app.get("/test")
async def say_hello(id: int,token=Header(None)):
    return {"id": id,"token":token}
@app.post("/login")
def login(data=Body(None)):
    return {"data":data}
@app.post("/login")
def login(username=Form(None),passwd=Form(None)):
    return {"data":{"username":username,"passwd":passwd}}
//username=coeleak&passwd=123456

返回定制信息

//返回json
@app.get("/user")
def user():
    return JSONResponse(content={"msg":"getuser"},status_code=233,headers={"a":"b"})
HTTP/1.1 233
Date: Sun, 21 May 2023 04:57:30 GMT
Server: uvicorn
A: b
Content-Length: 17
Content-Type: application/json
{"msg":"getuser"}
//返回HTML
@app.get("/user")
def user():
    html="""
    <html>
    <body>
    <p style="color:red">hello</p>
    </body>
    </html>
    """
    return HTMLResponse(html)
//返回文件
@app.get("/picture")
def picture():
    picture="col.jpg"
    return FileResponse(picture)

jinja2返回html

app = FastAPI()
template = Jinja2Templates("page")
@app.get("/")
def index(req:Request,username):
    return template.TemplateResponse("index.html",context={"request":req,"name":username})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>fastapi {{name}}</p>
</body>
</html>
:username})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>fastapi {{name}}</p>
</body>
</html>


目录
相关文章
|
10月前
|
存储 消息中间件 缓存
9 个 FastAPI 的必知资源
FastAPI 是 Python 开发人员最新、最流行的 API 框架之一。我们的工程师一次又一次需要将一个或多个第三方库与我们的 API 结合使用,以附加额外的功能和特性来丰富我们的项目。
425 0
|
11月前
|
JSON API 数据格式
FastApi的搭建与测试
FastApi的搭建与测试
190 0
|
网络架构 Python
FastApi-18-APIRouter
FastApi-18-APIRouter
342 0
|
28天前
|
JavaScript Shell API
FastAPI是什么?
FastAPI是一个现代、高性能的Python Web框架,专为构建API设计。它利用标准的Python类型提示,支持同步及异步编程,并借助Pydantic实现数据验证。FastAPI以卓越的性能媲美Node.js和Go,代码简洁优雅,能自动生成交互式API文档如Swagger UI和ReDoc,方便测试和调试。其对`async`和`await`的支持使之适用于WebSocket等高并发场景。快速上手仅需安装FastAPI和Uvicorn,编写少量代码即可启动服务并访问自动生成的文档界面。FastAPI不仅易于入门,还支持复杂的功能如依赖注入和后台任务,非常适合追求高性能和快速开发的项目。
|
1月前
|
Java API Python
Python 搭建 FastAPI 项目
Python 搭建 FastAPI 项目
34 0
|
4月前
|
安全 API Python
FastAPI入门指南
FastAPI是基于Python类型提示的高性能Web框架,用于构建现代API。它提供高性能、直观的编码体验,内置自动文档生成(支持OpenAPI)、数据验证和安全特性。安装FastAPI使用`pip install fastapi`,可选`uvicorn`作为服务器。简单示例展示如何定义路由和处理函数。通过Pydantic进行数据验证,`Depends`处理依赖。使用`uvicorn main:app --reload`启动应用。FastAPI简化API开发,适合高效构建API应用。5月更文挑战第21天
129 1
|
4月前
|
缓存 中间件 API
FastAPI
【2月更文挑战第1天】FastAPI是一个用于构建API的现代、快速的Python Web框架,具有以下特点:
113 9
|
4月前
|
JSON API 网络架构
FastAPI+React全栈开发13 FastAPI概述
FastAPI是一个高性能的Python Web框架,以其快速编码和代码清洁性著称,减少了开发者错误。它基于Starlette(一个ASGI框架)和Pydantic(用于数据验证)。Starlette提供了WebSocket支持、中间件等功能,而Pydantic利用Python类型提示在运行时进行数据验证。类型提示允许在编译时检查变量类型,提高开发效率。FastAPI通过Pydantic创建数据模型,确保数据结构的正确性。FastAPI还支持异步I/O,利用Python 3.6+的async/await关键词和ASGI,提高性能。此外,
175 0
|
4月前
|
Java API 数据库
FastAPI中如何调用同步函数
FastAPI中如何调用同步函数
185 0
|
4月前
|
缓存 监控 API
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
229 0