15

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)

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. 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. The callbacks also didn't help.

Sudip Kandel
  • 459
  • 1
  • 4
  • 9
  • Does this answer your question? [What is the proper way to make downstream Https requests inside of Uvicorn/FastAPI?](https://stackoverflow.com/questions/73721736/what-is-the-proper-way-to-make-downstream-https-requests-inside-of-uvicorn-fasta) – Chris Dec 25 '22 at 16:38
  • Related answers can be found [here](https://stackoverflow.com/a/74239367/17865804), as well as [here](https://stackoverflow.com/a/74556972/17865804) and [here](https://stackoverflow.com/a/71398460/17865804) – Chris Apr 25 '23 at 05:43

2 Answers2

12

I didn't exactly get the way to store response without returning using fastapi/starlette directly. But I found a workaround for completing this task.

  • For the people trying to implement same thing, Please consider this way.
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.

Sudip Kandel
  • 459
  • 1
  • 4
  • 9
  • 1
    The docs discuss a different method here: https://fastapi.tiangolo.com/advanced/openapi-callbacks/#an-app-with-callbacks I like your answer b/c it keeps the call within the route that requires the call (e.g., for captcha-related verification this can be handy). – Harley Lang Dec 11 '20 at 23:53
10

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.

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

T D
  • 111
  • 1
  • 3