fastAPI简单使用


前言

利用python fastAPI框架搭建简便的api服务


一、fastAPI是什么?

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。总之它可以简单快捷的创建api服务。

二、安装

1.fastapi的安装(此处用的是阿里云镜像源)

pip install fastapi -i https://mirrors.aliyun.com/pypi/simple
pip install uvicorn -i https://mirrors.aliyun.com/pypi/simple

2.测试一下

创建文件test.py,代码如下:

from fastapi import FastAPI

app = FastAPI()


@app.get('/')
def main():
	return {"message": "hello"}

然后打开终端(wins + R)启动uvicorn服务:

uvicorn test:app --reload
# 指定端口启动
uvicorn test:app --host '0.0.0.0' --port 8000 --reload

其中test 为文件名;app为test.py中创建的app对象;–reload为热启动,重启服务
在这里插入图片描述
看到如图结果代表启动成功。打开游览器输入127.0.0.1:8000/即可看到main方法中的输出结果。

三、使用

1.声明路径参数

from fastapi import FastAPI

app = FastAPI()


@app.get('/home/{key}')
def main(key):  # 这里可以标记key的类型,例如: def main(key: int)
	return {"key": key}
	

请求结果:
在这里插入图片描述

2. 声明路径参数有效值

from fastapi import FastAPI
from enum import Enum

app = FastAPI()


class limit(str, Enum):
    value1 = "111"
    value2 = "222"
    value3 = "333"


@app.get('/home/{key}')
def main(key: limit):
    return {"key": key}

超出限制范围的请求会返回告知你一个错误信息的json:
在这里插入图片描述

3. 声明路径参数为路径

from fastapi import FastAPI

app = FastAPI()


@app.get('/file/{file_path:file_path}')
def main(file_path):
	return {"path": file_path}
	

4. 声明params参数

from fastapi import FastAPI

app = FastAPI()


@app.get('/file')
def main(value1, value2):
	return {"value1": value1, "value2": value2}
	

使用浏览器访问http://127.0.0.1:8000/file?value1=ssss&value2=rrrrrrr,你会得到:{ "value1": "ssss", "value2": "rrrrrrr" }

5. 请求体(如post请求会用到)

定义请求体,需要使用 Pydantic

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


@app.get('/home')
def main(item: Item):
	return item


class Item(BaseModel):
    value1: str
    value2: str = None
    value3: float = None

用postman发送模拟post请求(请求体格式为json):
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值