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

2024-09-24 00:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

I want to store this response content without returning it.

是的,如果我返回函数,我将得到结果,但当我打印它时,我找不到结果。 另外,若我给出post请求,那个么我将得到找不到的错误实体

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


Tags: 文件tostoreapiurlresponse地方content
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/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')))

Please let me know if there are better approaches.

相关问题 更多 >