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月前
|
JSON API 数据格式
FastApi的搭建与测试
FastApi的搭建与测试
180 0
|
网络架构 Python
FastApi-18-APIRouter
FastApi-18-APIRouter
331 0
|
3月前
|
安全 API Python
FastAPI入门指南
FastAPI是基于Python类型提示的高性能Web框架,用于构建现代API。它提供高性能、直观的编码体验,内置自动文档生成(支持OpenAPI)、数据验证和安全特性。安装FastAPI使用`pip install fastapi`,可选`uvicorn`作为服务器。简单示例展示如何定义路由和处理函数。通过Pydantic进行数据验证,`Depends`处理依赖。使用`uvicorn main:app --reload`启动应用。FastAPI简化API开发,适合高效构建API应用。5月更文挑战第21天
102 1
|
3月前
|
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,提高性能。此外,
146 0
|
3月前
|
缓存 中间件 API
FastAPI
【2月更文挑战第1天】FastAPI是一个用于构建API的现代、快速的Python Web框架,具有以下特点:
101 8
|
3月前
|
缓存 监控 API
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
205 0
|
9月前
|
JSON API 数据格式
使用Python构建RESTful API:Flask和FastAPI的对比与实践
在现代Web开发中,构建RESTful API是一项常见任务。Python提供了多个框架来简化这个过程,其中Flask和FastAPI是两个备受欢迎的选择。本文将对比Flask和FastAPI,并通过实际示例展示它们的用法和优势。
|
JSON IDE 安全
FastAPI 是什么?快速上手指南
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建基于 Python 的 API。它是一个开源项目,基于 Starlette 和 Pydantic 库构建而成,提供了强大的功能和高效的性能。
FastAPI 是什么?快速上手指南
|
JSON API 数据格式
使用(Python)FastAPI快速构建你的后端接口服务
使用(Python)FastAPI快速构建你的后端接口服务
863 0
|
测试技术 数据库 C++
2023年是时候更新你的技术武器库了:Asgi vs Wsgi(FastAPI vs Flask)
也许这一篇的标题有那么一点不厚道,因为Asgi(Asynchronous Server Gateway Interface)毕竟是Wsgi(Web Server Gateway Interface)的扩展,而FastAPI毕竟也是站在Flask的肩膀上才有了突飞猛进的发展,大多数人听说Asgi也许是因为Django的最新版(3.0)早已宣布支持Asgi网络规范,这显然是一个振奋人心的消息,2023年,如果你在Web开发面试中不扯一点Asgi,显然就有点落后于形势了。
2023年是时候更新你的技术武器库了:Asgi vs Wsgi(FastAPI vs Flask)