Making HTTP Requests from a FastAPI Application to an External API
Last Updated :
26 Mar, 2024
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. Your FastAPI server may need to fetch data from other external APIs, to perform data aggregations and comparisons. So let's learn how to send HTTP requests to an external API from a FastAPI application.
Sending HTTP Requests from FastAPI to External APIs
Create a file main.py with the following code:
Python3
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {'message': 'Welcome to GeeksforGeeks!'}
Make a request to an external API
Now we will call another API inside our FastAPI application. Currently, we are using a simple test API for demonstration purposes.
https://jsonplaceholder.typicode.com/users
The data returned from the API looks like this:
external API call responseCalling an external API from our FastAPI server:
- Synchronous call
- Asynchronous call
Call external api from Web API Synchronously
If the API call is synchronous, it means that the code execution will block (or wait) for the API call to return before continuing. We will use the requests module in python, to make synchronous call to the external test API.
Open the terminal and use the following command to install the requests module.
pip install requests
Open the main.py file that we had created before. Here we will import the requests module.
import requests
Now we will make another endpoint: /get_firstuser . This will call the test API and synchronously return the name and username of the first user in the response. So our main.py file looks something like this.
Python3
from fastapi import FastAPI
import requests
app = FastAPI()
@app.get("/")
def root():
return {'message': 'Welcome to GeeksforGeeks!'}
@app.get('/get_firstuser')
def first_user():
api_url = "https://jsonplaceholder.typicode.com/users"
all_users = requests.get(api_url).json()
user1 = all_users[0]
name = user1["name"]
email = user1["email"]
return {'name': name, "email": email}
Call external api from Web API Asynchronous
If the API call is asynchronous, the program doesn't wait for the response. Instead, it continues executing other code while the API call is in progress. When the response is ready, the program will handle it. We will use httpx module in python to make the asynchronous API call.
Open the terminal and use the following command to install the httpx module.
pip install httpx
Open the main.py file that we had created before. Here we will import the httpx module.
import httpx
Now we will make another endpoint: /get_seconduser. This will asynchronously return the name and username of the second user in the response. So our main.py file looks something like this.
Python3
from fastapi import FastAPI
import requests
import httpx
app = FastAPI()
@app.get("/")
def root():
return {'message': 'Welcome to GeeksforGeeks!'}
@app.get('/get_firstuser')
def first_user():
api_url = "https://jsonplaceholder.typicode.com/users"
all_users = requests.get(api_url).json()
user1 = all_users[0]
name = user1["name"]
email = user1["email"]
return {'name': name, "email": email}
@app.get('/get_seconduser')
async def second_user():
api_url = "https://jsonplaceholder.typicode.com/users"
async with httpx.AsyncClient() as client:
response = await client.get(api_url)
all_users = response.json()
user2 = all_users[1]
name = user2["name"]
email = user2["email"]
return {'name': name, "email": email}
Testing the API
Now open the terminal in your directory and run the server with the following command:
uvicorn main:app --reload
Now you can open the browser and call your API at http://localhost:8000. If you enter http://127.0.0.1:8000/get_firstuser, the FastAPI server makes a call to the external test API and returns the name and email of the first user as response.
FastAPI response for first userIf you enter http://127.0.0.1:8000/get_seconduser, you will be get the name and email of the second user as response.
FastAPI response for second userYou can also refer to this article, which explains the benefit of using asynchronous API calls instead of synchronous API calls.
Similar Reads
Creating First REST API with FastAPI FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we'll walk you through the steps to create your very first REST API using FastAPI. By the end, you'll have a solid foundation for building and deploying APIs with
5 min read
Build an API Gateway REST API with HTTP Integration Pre-requisite: AWS We can use either the HTTP proxy integration or the HTTP custom integration to build an API using HTTP integration. When feasible, leverage HTTP proxy integration for faster API setup while delivering varied and strong functionality. If it is essential to change client request dat
4 min read
Create and Send API Requests in Postman Postman serves as a flexible tool, simplifying the system of crafting and checking out API requests. In the world of software, APIs(Application Programming Interfaces) are the constructing blocks for packages to speak with each other. In this article, you will find out how Postman turns into your go
4 min read
Testing FastAPI Application The web framework in Python that is used for creating modern and fast APIs is called FastAPI. Once we have created the FastAPI, there is a need to test if the API is working fine or not according to the requirements. In this article, we will discuss the various ways to test the FastAPI application.
3 min read
How To Use Axios NPM to Generate HTTP Requests ? In this article, we are going to learn about Axios and HTTP requests and using Axios to generate HTTP requests. Axios is a promise-based HTTP library that is used by developers to make requests to their APIs or third-party API endpoints to fetch data. It is a popular JavaScript library used for maki
8 min read
API Management and Consumption Patterns in Cloud Native Applications In the world of cloud-native applications, it is crucial to design and manage APIs effectively. APIs are the foundation for software applications to communicate with each other and with users. Cloud-native applications are specially designed to work well in cloud environments, using the benefits of
7 min read
Create a REST API as an Amazon S3 Proxy in API Gateway Automation Amazon Web Services is a leading cloud provider which provides us with plenty of Paas, and Iaas, and services that we can use to build and deploy our applications. we gonna build and Deploy a REST API with API Gateway which acts as a proxy to S3 and can be used to perform Read/Write on S3 without an
5 min read
Fetching and Displaying Data with HTMX and FastAPI HTMX allows us to utilize current AJAX methods in HTML directly, while FastAPI is a strong backend framework for quick and efficient API development. This artilce will examine the way of combining HTMX with FastAPI to develop dynamic web applications. Setting Up FastAPIStep1. First we need Python in
3 min read
Deploying FastAPI Applications Using Render Deploying FastAPI applications involves making your FastAPI-based web application accessible over the internet or an intranet so that users can interact with it. FastAPI is a modern, fast (hence the name), web framework for building APIs with Python, known for its simplicity and performance. This ar
4 min read
Send Parameters to POST Request FastAPI In the world of web development and API creation, sending parameters via a POST request is a fundamental operation. FastAPI, a modern Python web framework, simplifies this process and allows developers to build efficient and scalable APIs. In this article, we will explore the theory and practical as
3 min read