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

推荐订阅源

小众软件
小众软件
WordPress大学
WordPress大学
IT之家
IT之家
G
Google Developers Blog
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
博客园 - 三生石上(FineUI控件)
Engineering at Meta
Engineering at Meta
Martin Fowler
Martin Fowler
V
V2EX
爱范儿
爱范儿
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
V
Visual Studio Blog
有赞技术团队
有赞技术团队
I
InfoQ
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网

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 API Testing Frameworks in the Real World: A Prac...
RODRIGO SIDNEY COLQUE QUISPE · 2026-06-27 · via DEV Community

RODRIGO SIDNEY COLQUE QUISPE

Applying API Testing Frameworks in the Real World: A Practical Guide with Pytest

In today's interconnected software landscape, Application Programming Interfaces (APIs) are the bridges that allow different systems to communicate. With the growing reliance on microservices and third-party integrations, ensuring that your APIs are robust, secure, and performant is no longer optional—it's critical.

This is where API testing frameworks come in. In this article, we'll explore how to apply API testing in the real world using Python and Pytest, one of the most popular and powerful testing frameworks available.

Why Do We Need API Testing Frameworks?

Manual testing using tools like Postman or Insomnia is great for exploration, but it doesn't scale. When you have hundreds of endpoints and continuous integration/continuous deployment (CI/CD) pipelines, you need automated frameworks to:

  1. Ensure Reliability: Catch breaking changes before they reach production.
  2. Validate Business Logic: Verify that the API returns the correct data for both valid and invalid inputs.
  3. Check Performance and Security: Ensure the API can handle load and is secure against common vulnerabilities.

The Tooling: Python, Pytest, and Requests

For our real-world example, we'll use:

  • Python: A versatile language widely used for test automation.
  • Pytest: A mature testing framework that makes writing small tests easy, yet scales to support complex functional testing.
  • Requests: The elegant and simple HTTP library for Python to make API calls.

Real-World Scenario: Testing a User Management API

Imagine we are building a backend for a social media application. We have an API endpoint to retrieve user profiles. We need to ensure that:

  1. A valid request returns a 200 OK status and the correct user data structure.
  2. Requesting a non-existent user returns a 404 Not Found status.

Let's write tests for a mock API (e.g., https://reqres.in/api/users).

Step 1: Setting up the environment

First, install the necessary packages:

pip install pytest requests

Step 2: Writing our first tests

Create a file named test_users_api.py and add the following code:

import requests
import pytest

BASE_URL = "https://reqres.in/api"

def test_get_valid_user():
    """
    Test that retrieving an existing user returns a 200 status code
    and the correct data structure.
    """
    user_id = 2
    response = requests.get(f"{BASE_URL}/users/{user_id}")

    # 1. Assert Status Code
    assert response.status_code == 200, f"Expected 200, but got {response.status_code}"

    # 2. Parse JSON response
    response_data = response.json()

    # 3. Assert Data Structure and Content
    assert "data" in response_data
    assert response_data["data"]["id"] == user_id
    assert "email" in response_data["data"]
    assert "first_name" in response_data["data"]

def test_get_nonexistent_user():
    """
    Test that retrieving a user that does not exist returns a 404 status code.
    """
    user_id = 9999  # Assuming this user doesn't exist
    response = requests.get(f"{BASE_URL}/users/{user_id}")

    # Assert Status Code
    assert response.status_code == 404, f"Expected 404, but got {response.status_code}"

    # Check that the response is empty as expected by this mock API
    assert response.json() == {}

Step 3: Running the tests

Execute the tests in your terminal using the pytest command:

pytest test_users_api.py -v

Output:

============================= test session starts ==============================
...
test_users_api.py::test_get_valid_user PASSED                            [ 50%]
test_users_api.py::test_get_nonexistent_user PASSED                      [100%]

============================== 2 passed in 0.45s ===============================

Advanced Real-World Practices

While the example above is simple, real-world API testing frameworks incorporate more advanced patterns:

1. Data-Driven Testing with @pytest.mark.parametrize

Instead of writing separate functions for every edge case, you can parameterize your tests.

@pytest.mark.parametrize("user_id, expected_status", [
    (1, 200),
    (2, 200),
    (999, 404)
])
def test_get_users_status(user_id, expected_status):
    response = requests.get(f"{BASE_URL}/users/{user_id}")
    assert response.status_code == expected_status

2. Authentication and Setup with Pytest Fixtures

If your API requires authentication (e.g., Bearer tokens), you shouldn't log in inside every test. Use fixtures to handle setup and teardown.

@pytest.fixture(scope="session")
def api_token():
    # Code to authenticate and get token
    # login_response = requests.post(f"{BASE_URL}/login", json={"email": "...", "password": "..."})
    # return login_response.json()["token"]
    return "mock_token_123"

def test_secure_endpoint(api_token):
    headers = {"Authorization": f"Bearer {api_token}"}
    response = requests.get(f"{BASE_URL}/secure-data", headers=headers)
    # ... assertions

3. Schema Validation

In the real world, APIs evolve. Instead of manually asserting every key in a JSON response, use schema validation libraries like Cerberus or jsonschema to ensure the response payload matches the expected contract.

Conclusion

Building a robust API testing framework is an investment that pays off exponentially as your application grows. By leveraging Python, requests, and the powerful features of pytest like parametrization and fixtures, you can create a test suite that is easy to maintain, highly readable, and perfectly suited for CI/CD pipelines.

Start small, automate your most critical endpoints first, and gradually build out your coverage. Happy testing!