[英]How to call an api from another api in fastapi?
I was able to get the response of one API from another but unable to store it somewhere(in a file or something before returning the response) response=RedirectResponse(url="/apiname/")
(I want to access a post request with header and body)我能够从另一个获得一个 API 的响应,但无法将其存储在某个地方(在返回响应之前在文件或其他东西中)
response=RedirectResponse(url="/apiname/")
(我想访问一个发布请求header 和正文)
I want to store this response content without returning it.
我想存储这个响应内容而不返回它。
Yes, if I return the function I will get the results but when I print it I don't find results.是的,如果我返回 function,我会得到结果,但是当我打印它时,我找不到结果。 Also, if I give post request then I get error Entity not found.
另外,如果我发出发帖请求,则会收到错误消息,找不到实体。
I read the starlette and fastapi docs but couldn't get the workaround.我阅读了 starlette 和 fastapi 文档,但无法找到解决方法。 The callbacks also didn't help.
回调也没有帮助。
I didn't exactly get the way to store response without returning using fastapi/starlette directly.如果不直接使用fastapi/starlette返回,我并没有完全得到存储响应的方法。 But I found a workaround for completing this task.
但我找到了完成此任务的解决方法。
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.
如果有更好的方法,请告诉我。
I have the same problem & I needed to call the third-party API with async way So I tried many ways & I came solution with requests-async library and it works for me.我有同样的问题,我需要用异步方式调用第三方 API 所以我尝试了很多方法,我用requests-async库来解决它,它对我有用。
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 also you can use this video he is using httpx httpx你也可以使用他正在使用 httpx 的这个视频
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.