fastapi之helloworld
2021/7/14 6:07:47
本文主要是介绍fastapi之helloworld,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
简介
以下简介来自官网描述:
FastAPI是一个用于构建API的现代、快速(高性能)的web框架,使用Python3.6+并基于标准的Python类型提示。
关键特性:
- 快速:可与NodeJS和Go比肩的极高性能。最快的Python Web框架之一。(PS:自行用wrk测试了一下,比flask快2倍,但比sanic慢一截,更不提Go Gin)
- 高效编码:提高功能开发速度约200%至300%。(PS:选择Python做后端就是为了开发快)
- 更少Bug:减少约40%的人为(开发者)导致的错误。
- 智能:极佳的编辑器支持。处处皆可自动补全,减少调试时间。
- 简单:设计易于使用和学习,阅读文档更短。
- 简短:使代码重复最小化。通过不同的参数声明实现丰富功能。
- 健壮:生产可用级别的代码。还有自动生成的交互式文档
- 标准化:基于(并完全兼容)API的相关开放标准:OpenAPI
安装
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
命令说明:
hello
: hello.py文件app
: 在hello.py文件中通过FastAPI()
创建的对象--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请求,可以在文档页调试这个接口测试。
这篇关于fastapi之helloworld的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南
- 2024-09-30Dnd-Kit学习:新手快速入门指南