How to call an api from another api in fastapi?

Member

by dana , in category: Javascript , 2 months ago

How to call an api from another api in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 2 months ago

@dana 

In FastAPI, you can call an API from another API by using the requests library to make HTTP requests.


Here's an example of how you can call an API from another API in FastAPI:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from fastapi import FastAPI
import requests

app = FastAPI()

@app.get("/get_data_from_external_api")
async def get_data_from_external_api():
    response = requests.get("https://api.example.com/data")
    
    if response.status_code == 200:
        data = response.json()
        return data
    else:
        return {"error": "Failed to fetch data from external API"}


In the above code, we define a route /get_data_from_external_api that makes a GET request to an external API https://api.example.com/data using the requests library. If the request is successful (status code 200), we return the data from the external API. Otherwise, we return an error message.


Make sure to install the requests library by running pip install requests before running the above code.