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
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms. What is an API?An API is a set of
10 min read
Simple chat Application using Websockets with FastAPI
In this article, we'll delve into the concept of WebSockets and their role in facilitating bidirectional communication between clients and servers. Subsequently, we'll embark on the journey of building a real-time multi-client chat application. This application will empower numerous users to connect
6 min read
How to make a request using HTTP basic authentication with PHP curl?
Making secure API requests is a common requirement in web development, and PHP provides a powerful tool for this purpose, which is cURL. The challenge is to seamlessly integrate HTTP basic authentication with PHP cURL for secure API communication. This involves not only transmitting sensitive user c
3 min read
How to pass parameters in Postman requests?
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), save environments for later use, and convert the API to code for various languages(like JavaScript, and Python). In this
2 min read
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
How to Make an HTTP Request with Android?
In any Android Application, there is only so much a user can do without an internet connection. All modern Android Applications interact with resources available online or a backend-specific to the app. In this article, we will look at one of the ways through which we can retrieve and post resources
6 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