惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
人人都是产品经理
人人都是产品经理
量子位
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
月光博客
月光博客
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Visual Studio Blog
博客园 - 叶小钗
博客园 - 司徒正美
美团技术团队
博客园_首页
宝玉的分享
宝玉的分享
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
D
DataBreaches.Net
Google DeepMind News
Google DeepMind News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Applying Pytest and Requests for Real-World API Testing i...
Abel Fernando PACOMPIA ORTIZ · 2026-06-27 · via DEV Community

Introduction

API testing is an essential practice for validating backend applications before they are deployed. In this project, I built a small FastAPI application and tested its endpoints using Pytest and FastAPI TestClient. The goal is to show a practical and academic example of how automated API tests can improve reliability.

What is API Testing?

API testing verifies the behavior of application endpoints. Instead of checking visual elements, API tests send HTTP requests and validate status codes, response bodies, data formats, and error handling.

Why API Testing is Important

Modern applications often depend on APIs to connect frontends, services, databases, and external systems. If an API endpoint fails, many parts of the system can be affected. Automated API tests help detect problems early and provide confidence when making changes.

API Testing Frameworks Comparative

Framework Language / Ecosystem Best use case Automation support
Pytest + Requests / TestClient Python Developer-friendly automated API tests Excellent with CI/CD tools
Postman + Newman JavaScript / CLI ecosystem Manual and automated API collections Good for pipeline execution
Rest Assured Java API testing in Java projects Strong with Maven, Gradle, and CI
Karate DSL Java / DSL BDD-style API tests with readable scenarios Good CI/CD integration

Why I Chose Pytest

I chose Pytest because it is simple, readable, and widely used in Python projects. It allows developers to write test functions with plain assertions, and it integrates easily with FastAPI through TestClient.

Demo API with FastAPI

The demo API provides endpoints for a welcome message, health check, listing users, retrieving a user by id, and creating a new user in memory.

Example from app/main.py:

@app.get("/users/{user_id}", response_model=User)
def get_user_by_id(user_id: int) -> User:
    """Return one user by id or a clear 404 error."""
    for user in users:
        if user.id == user_id:
            return user

    raise HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail=f"User with id {user_id} was not found.",
    )

Writing Real-World API Test Cases

The test suite checks successful responses, response content, list structures, user lookup, error handling, and validation failures.

Example from tests/test_api.py:

def test_health_check_returns_ok():
    # Validates that the health endpoint reports the API as available.
    response = client.get("/health")

    assert response.status_code == 200
    assert response.json() == {"status": "ok"}

Running the Tests Locally

To install dependencies and run the tests:

python -m pip install -r requirements.txt
pytest -v

Automating API Tests with GitHub Actions

GitHub Actions can run the test suite automatically when code is pushed or when a pull request is opened.

Example from .github/workflows/api-tests.yml:

name: API Tests with Pytest

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  api-tests:
    runs-on: ubuntu-latest

Results

The project includes seven API tests that validate the main behavior of the demo application. These tests can be executed locally with Pytest and automatically in GitHub Actions.

Conclusion

Pytest is a strong option for API testing in Python because it is readable, flexible, and easy to automate. Combined with FastAPI and GitHub Actions, it supports a simple but effective workflow for validating backend behavior before deployment.

GitHub Repository Link

GitHub repository: https://github.com/Abel-GG-777/api-testing-pytest-demo.git