Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
What is Application Testing?
Next article icon

Testing FastAPI Application

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Testing FastAPI Application

Below are the methods by which we can test FastAPI applications:

  • Using TestClient library
  • Using Requests library

Using TestClient Library

The HTTPX-based library which is used to call the asynchronous FastAPI application is known as the TestClient library. In this method, we will see how we can test FastAPI applications using the TestClient library.

Syntax

client = TestClient(app)

def function_name():

response = client.get("/")

assert response.status_code == status_code

assert response.json() == {"msg": "Message_FastAPI"}

Here,

  • function_name: It is the name of the function which you want to call while testing.
  • status_code: It is the HTTP status code which we want to display to user along with message.
  • Message_FastAPI: It is the messages shown to user along with the response.

Example: In this example, we are creating a function which returns a certain message and then we are matching that message with other message defined using TestClient.

Python3
# Import the FastAPI and TestClient libraries from fastapi import FastAPI from fastapi.testclient import TestClient  # Create a FastAPI application app = FastAPI()  # Call FastAPI using Pydantic @app.get("/") async def read_main():     return {"msg": "Welcome to Geeks For Geeks"}  # Create a Test Client for FastAPI app client = TestClient(app)  # Test FastAPI using TestClient def test_read_main():     response = client.get("/")     assert response.status_code == 200     assert response.json() == {"msg": "Welcome to Geeks For Geeks"} 

Now, open the terminal and run the following command to test the FastAPI application created.

pytest main.py

Output


Screenshot-from-2023-11-28-14-27-39

Using Requests Library

The library which is used to send HTTP requests using Python is known as requests library. In this method, we will see how we can test FastAPI applications using requests library. For testing FastAPI applications using requests library, the user needs to create a separate test file.

Syntax

import requests

print(requests.get("http://127.0.0.1:8000/").json())

Example: In this example, we have created a function with two messages, msg and test_msg, which we are checking if these messages are same, then 'Test Passed' message is displayed, else 'Test Failed' message is displayed.

Python3
# Import the FastAPI library from fastapi import FastAPI  # Create a FastAPI application app = FastAPI()  # Call FastAPI using Pydantic @app.get("/") async def read_main():     msg="Welcome to Geeks For Geeks"     test_msg="Welcome to Geeks For Geeks"     if msg==test_msg:         return {"msg": "Test Passed"}     else:         return {"msg": "Test Failed"} 

Now, open the terminal and run the following command to run your FastAPI application. This command will also let the app to reload in case of any changes made in app.

uvicorn main:app --reload

test.py: This file is used created to test the above main file program.

Python3
# Import the requests library import requests  # Test FastAPI using requests library print(requests.get("http://127.0.0.1:8000/").json()) 

Output

Screenshot-from-2023-11-28-14-32-35



Next Article
What is Application Testing?

I

ishita28rai
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • FastAPI
  • Geeks Premier League 2023
  • Python Testing
Practice Tags :
  • python

Similar Reads

  • Load testing applications
    The importance of load testing cannot be emphasized in the current digital environment, where apps must function flawlessly and be reliable. Applications that are load tested are a crucial procedure that tests an application's resilience in real-world scenarios. Table of Content What is Load Testing
    13 min read
  • What is Application Testing?
    Application testing is an essential part of the software development process to maintain the standards of the application and its capabilities of providing the functionality for which it is being developed. As much as the user interface is checked to ensure that it meets the needs of the users, func
    15+ min read
  • Software Testing - Bank Domain Application Testing
    Banking domain application testing (BDAT) refers to testing an application that is developed especially for banks for performing all required functionalities like transactions, loan approval, managing different types of bank cards, and much more, the functionality depends on the size and type of ban
    13 min read
  • TestNG + Spring Integration Example
    TestNG is the popular testing framework inspired by JUnit and designed to cover a wider range of testing needs, including unit testing, and end-to-end testing. Spring is the powerful framework for building enterprise applications in Java. Integrating the TestNG with Spring can allow you to leverage
    6 min read
  • Test Cases For API Testing
    API testing mainly focuses on understanding what APIs are and why testing them is crucial for Software application development. This section sets the stage for the rest of the document by outlining the importance of API testing ensuring robust and reliable software In this article we explain Test Ca
    6 min read
  • Test Plan - Software Testing
    Software testing is important to make sure applications work properly and meet user needs. A clear and detailed test plan is the foundation of successful testing, guiding everything from creating test cases to fixing issues. In this article, we will break down what a test plan is, why it’s important
    15+ min read
  • Testing an Android Application with Example
    Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including
    5 min read
  • Specification-Based Testing
    Specification-based testing is a black-box testing technique that uses the specifications of a system to derive test cases. The specifications can be functional or non-functional and can be at different levels of abstraction, such as user requirements, system requirements, or design specifications.
    11 min read
  • Postman vs Apidog for API Testing
    API testing is the practice of ensuring that an API works as intended. It can be conducted manually by developers or automated using an API testing tool. There are several sorts of API testing, and each one serves a unique role in guaranteeing the API's reliability. In this article, we'll learn abou
    5 min read
  • Python Falcon - Testing
    Testing is an integral part of software development, ensuring the reliability and functionality of applications. Python Falcon is a lightweight web framework for building APIs rapidly. In this article, we will explore how to test Python Falcon APIs using two popular testing frameworks: unittest and
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences