Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐Ÿš€ What is FastAPI๐Ÿ“š Creating Your First API๐Ÿ“š Running the Server๐Ÿ“š HTTP Methods๐Ÿ“š API Endpoints๐Ÿ“š Request and Response๐Ÿ“š Documentation๐Ÿ“š Testing Basics
Fastapi/Api Basics/Testing Basics

Testing API Basics ๐Ÿงช

Testing ensures your API works correctly. FastAPI makes it easy with the TestClient.

Setting Up Tests

Install pytest:

pip install pytest httpx

Create `test_main.py`:

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}

Run tests:

pytest

Testing Endpoints

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_get_item():
    response = client.get("/items/1")
    assert response.status_code == 200
    assert response.json()["id"] == 1

def test_create_item():
    response = client.post("/items", json={"name": "Test", "price": 10.0})
    assert response.status_code == 201
    assert response.json()["name"] == "Test"

Testing with Different Status Codes

def test_not_found():
    response = client.get("/items/999")
    assert response.status_code == 404

def test_bad_request():
    response = client.post("/items", json={"price": "invalid"})
    assert response.status_code == 422

Testing Request Body

def test_create_user():
    response = client.post("/users", json={
        "name": "John",
        "email": "john@example.com"
    })
    assert response.status_code == 201
    assert response.json()["name"] == "John"

Running Tests

# Run all tests
pytest

# Run specific file
pytest test_main.py

# Run with verbose output
pytest -v

# Run specific test
pytest test_main.py::test_read_root

๐Ÿ”‘ Key Takeaways

  • โœ… Use TestClient to test endpoints
  • โœ… Check status codes
  • โœ… Verify response data
  • โœ… Test error cases
  • โœ… Use pytest framework

Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep โ€ข Build Real โ€ข Verify Skills โ€ข Launch Forward

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn