How to call an api from another api in fastapi?

Sudip Kandel picture Sudip Kandel · Aug 19, 2020 · Viewed 12k times · Source

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.

Answer

Sudip Kandel picture Sudip Kandel · Aug 20, 2020

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.