如何从fastapi中的另一个api调用一个api?

Posted

技术标签:

【中文标题】如何从fastapi中的另一个api调用一个api?【英文标题】:How to call an api from another api in fastapi? 【发布时间】:2020-12-08 12:02:42 【问题描述】:

我能够从另一个 API 获得响应,但无法将其存储在某处(在返回响应之前的文件或其他内容中) response=RedirectResponse(url="/apiname/")(我想访问一个带有header和body的post请求)

我想存储这个响应内容而不返回它。

是的,如果我返回函数,我会得到结果,但是当我打印它时,我找不到结果。 另外,如果我发出 post 请求,则会收到错误 Entity not found。

我阅读了 starlette 和 fastapi 文档,但找不到解决方法。回调也没有帮助。

【问题讨论】:

【参考方案1】:

如果不直接使用 fastapi/starlette 返回,我并没有完全获得存储响应的方法。但我找到了完成此任务的解决方法。

对于尝试实现相同功能的人,请考虑这一点 方式。
import requests

def test_function(request: Request, path_parameter: path_param):

    request_example = "test" : "in"
    host = request.client.host
    data_source_id = path_parameter.id

    get_test_url= f"http://host/test/id/"
    get_inp_url = f"http://host/test/id/inp"

    test_get_response = requests.get(get_test_url)
    inp_post_response = requests.post(get_inp_url , json=request_example)
    if inp_post_response .status_code == 200:
        print(json.loads(test_get_response.content.decode('utf-8')))

如果有更好的方法,请告诉我。

【讨论】:

文档在这里讨论了一种不同的方法:fastapi.tiangolo.com/advanced/openapi-callbacks/…我喜欢你的回答 b/c 它将呼叫保持在需要呼叫的路由内(例如,对于与验证码相关的验证,这可能很方便) .【参考方案2】:

我有同样的问题&我需要用 async 方式调用第三方 API 所以我尝试了很多方法,我用requests-async library解决了 它对我有用。

import http3

client = http3.AsyncClient()

async def call_api(url: str):

    r = await client.get(url)
    return r.text

@app.get("/")
async def root():
    ...
    result_1 = await call_api('url_1')
    result_2 = await call_api('url_2')
    ...

httpx 你也可以使用 this video他正在使用httpx

【讨论】:

以上是关于如何从fastapi中的另一个api调用一个api?的主要内容,如果未能解决你的问题,请参考以下文章