python3写一个http接口服务(get, post),给别人调用3--fastapi

本文详细介绍如何使用FastAPI框架创建高性能的HTTP接口服务。包括GET和POST接口的代码实现,以及如何通过Uvicorn运行服务。FastAPI具备快速编码、减少错误、直观易用的特点,适合构建基于Python类型的API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、python3写一个http接口服务,给别人调用3--fastapi

        这次选择fastapi,FastAPI是一个现代的、快速(高性能)的web框架,用于基于标准Python类型提示使用Python 3.6+构建api。具有快速、快速编码、更少的错误、直观、简单、简便、健壮。简易而且本地win10能够跑起来。

二、FastAPI的get接口代码实现

        1.  安装:  pip install fastapi

                       pip install uvicorn

        2.  代码:  

# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2019/11/12 21:27
# @author  : Mo
# @function: get service of fastapi

from fastapi import FastAPI

app = FastAPI()

@app.get('/test/a={a}/b={b}')
def calculate(a: int=None, b: int=None):
    c = a + b
    res = {"res":c}
    return res


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app=app,
                host="0.0.0.0",
                port=8080,
                workers=1)

        3.  接口访问:http://127.0.0.1:8080/test/a=1/b=4

             浏览器访问结果:

                     

             postman访问结果:

                     

三、FastAPI的post接口代码实现

        1.  安装:  pip install fastapi

                       pip install uvicorn

        2.  代码:  

# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2019/11/12 21:27
# @author  : Mo
# @function: post service of fastapi

from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class Item(BaseModel):
    a: int = None
    b: int = None

@app.post('/test')
def calculate(request_data: Item):
    a = request_data.a
    b = request_data.b
    c = a + b
    res = {"res":c}
    return res

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app=app,
                host="0.0.0.0",
                port=8080,
                workers=1)

        3.  接口访问:http://127.0.0.1:8080/test

             postman访问结果:

                  

希望对你有所帮助!

评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值