Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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.

like image 640
Sudip Kandel Avatar asked Aug 19 '20 08:08

Sudip Kandel


People also ask

How do I pass a request in FastAPI?

Use the Request object directly For that you need to access the request directly. By declaring a path operation function parameter with the type being the Request FastAPI will know to pass the Request in that parameter.


2 Answers

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.

like image 165
Sudip Kandel Avatar answered Oct 29 '22 01:10

Sudip Kandel


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

like image 27
T D Avatar answered Oct 29 '22 01:10

T D