API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Testing APIs
  • Introduction
  • Table of Contents
  • API Academy
    • Get Started
      • What is an API?
      • How Does an API Work?
      • How to Call an API?
      • How to Read an API Documentation?
      • Chapter Summary
      • Get realtime weather
    • API Fundamentals
      • API Funtamentals: Overview
      • Method & Path
      • Parameters
      • Request Body
      • Responses
      • API Specification & OAS
      • Chapter Summary
    • Working with APIs
      • Working with APIs: Overview
      • Making Requests from Spec
      • Environments and Variables
      • Chaining Multiple Endpoints
      • Handling Authentication
      • Handling API Signatures
      • Introduction to Scripts
      • Chapter Summary
    • Mocking APIs
      • Mocking APIs: Overview
      • Smart Mock
      • Mock Expectations
      • Cloud Mock
      • Mock Scripts
      • Chapter Summary
    • Designing APIs
      • Designing APIs: Overview
      • Introduction to API Design
      • Creating Your First API Project
      • Analyzing Requirements and Planning Your API
      • Designing Data Models
      • Designing Endpoints
      • Using Components and Reusability
      • Setting Up Authentication
      • API Design Guidelines
      • Chapter Summary
    • Developing APIs
      • Developing APIs: Overview
      • Setup: Install Your AI Coding Assistant
      • Quick Start: From Spec to Running API in 30 Minutes
      • Understanding the Generated Code
      • Testing Your API with Apidog
      • Deployment: Put Your API Online
      • Chapter Summary
    • Testing APIs
      • Testing APIs: Overview
      • Getting Started: Your First Test Scenario
      • Integration Testing and Data Passing
      • Dynamic Values
      • Assertions and Validations
      • Flow Control: If, For, ForEach
      • Data-Driven Testing
      • Performance Testing
      • Test Reports and Analysis
      • CI/CD Integration
      • Scheduled Tasks and Automation
      • Advanced Testing Strategies
      • Chapter Summary
    • API Documentations
      • API Documentations: Overview
      • Publishing Your First API Doc
      • Customizing Documentation Appearance
      • Interactive Features for Consumers
      • Advanced Publishing Settings
      • Managing API Versions
      • Chapter Summary
    • Advanced API Technologies
      • API Technologies: Overview
      • GraphQL
      • gRPC
      • WebSocket
      • Socket.IO
      • Server-Sent Events (SSE)
      • SOAP
      • Chapter Summary
    • API Lifecycle
      • API Lifecycle: Overview
      • Stages of the API Lifecycle
      • API Governance
      • API Security Best Practices
      • Monitoring and Analytics
      • API Versioning Strategies
      • The Future of APIs
      • Chapter Summary
    • API Security
      • API Security: Overview
      • API Security Fundamentals
      • Authentication vs Authorization
      • Understanding OAuth 2.0 and OpenID Connect
      • JSON Web Tokens (JWT)
      • OWASP API Security Top 10
      • Encryption and HTTPS
      • Chapter Summary
    • API Tools
      • API Tools: Overview
      • The Evolution of API Tools
      • API Clients
      • Command Line Tools (cURL, HTTPie)
      • API Design and Documentation Tools
      • API Mocking Tools
      • API Testing Tools
      • All-in-One API Platforms
      • Chapter Summary
    • API Gateway
      • API Gateway: Overview
      • What is an API Gateway?
      • Key Features of API Gateways
      • API Gateway vs Load Balancer vs Service Mesh
      • Popular API Gateway Solutions
      • The BFF (Backend for Frontend) Pattern
      • Chapter Summary
  • Modern Pet Store
    • Pet
      • Get Pet
      • Update Pet
      • Delete Pet
      • Create Pet
      • List Pets
      • Upload Pet Image
    • User
      • Update User
      • Get User
      • Delete User
      • Login
      • Logout
      • Create User
    • Store
      • List Inventory
      • Create Order
      • Get Order
      • Delete Order
      • Callback Example
      • Pay for an Order
    • Payments
      • Pay Order
    • Chat
      • Create Chat Completion
    • Webhooks
      • Pet Adopted Event
      • New Pet Available Event
  • Schemas
    • Pet
    • Category
    • User
    • ApiResponse
    • OrderPayment
    • Tag
    • Order
    • Links-Order
    • PetCollection
    • Bank Card
    • Bank Account
    • Links
    • Error
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Testing APIs

Assertions and Validations

So far, we've built test scenarios that send requests and pass data. But how do we know if the API is actually working correctly? A request might return 200 OK but send back empty data, or worst, wrong data.
Assertions are the checkpoints of your testing. They automatically verify that the API response matches your expectations. In this chapter, we'll master both standard response assertions and powerful database validations.

What are Assertions?#

An assertion is simply a statement that must be true for your test to pass. Without assertions, your test essentially says, "I sent a request, and the server replied." It confirms communication but not correctness.
With assertions, your test becomes specific: "I sent a request, and I expect the status code to be 201, and the returned user ID to be a number." If this expectation isn't met, the test fails immediately, alerting you to the problem.

Why Use Assertions?#

You might think, "I can just look at the response and see if it's correct." For a single manual test, sure, you can eyeballing the JSON and say, "Yup, looks good."
But automated testing is blind. The computer needs explicit instructions—assertions—to judge pass or fail. This becomes critical during Regression Testing. If you deploy a new version weekly, you need a safety net that instantly validates hundreds of test cases. You can't manually check historical responses every time; assertions do that for you.

Adding Your First Assertion#

Apidog makes adding assertions incredibly easy—no coding required for most common cases.

Method: The "Post-processors" Tab#

1.
Open your request (e.g., POST /users).
2.
Go to the Post-processors tab.
3.
Click Add Post-processor -> Assertion.
Adding Assertion

Select Assertion Target#

You can check almost anything: Status code, Headers, JSON Body, etc.
Assertion Target Selection
You'll see a detailed form for configuring your assertion rule:
Name: Give your assertion a clear name (e.g., "Verify User ID").
Target Object: Choose where the data comes from (usually Response JSON or Response Header).
JSONPath Expression: The specific field you want to check (e.g., $.data.id).
Assertion: The rule to apply (e.g., Equals, Is Not Null) and the expected value.

Common Assertion Patterns#

Here are the most common things you should check:
1.
Status Code: The first line of defense.
Response.status.code Equals 200 (Success)
Response.status.code Equals 404 (Not Found)
2.
Response Time: Ensure performance.
Response.time Less than 500 (ms)
3.
JSON Body Values: Verify specific data.
$.email Equals test@example.com
$.id Exists (Not null)
4.
Header Values: Check content type or auth headers.
Response.header.Content-Type Contains application/json
See details Assertions
Pro Tip: You can also add assertions directly from the APIs > Request tab by clicking on the response field!
Assertion on Actual Response

Automatic Response Validation#

Tired of checking every field manually? Apidog has a built-in feature called Response Validation that does the heavy lifting for you.
When enabled, Apidog compares the actual API response against the Response Definition (Schema) you defined in your API documentation.
1.
In your request settings, look for the Response Validation toggle.
2.
If the API returns a string where a number is expected, or misses a required field, the test will automatically fail.
3.
This ensures your implementation stays strictly in sync with your API design contract.

Real Case: Validating User Registration#

Let's verify our POST /users endpoint from the previous chapter. When we create a user, we expect a very specific outcome.
Our Expectations:
1.
Status must be 201 Created (or 200).
2.
Response must contain the new id.
3.
Response must contain the same email we sent.
4.
Response must NOT contain the password (security check).
Configuration in Apidog:
SubjectComparatorValueDescription
Response.status.codeEquals201Verify creation success
$.idExist(Empty)Verify ID is returned
$.emailEquals{{newUserName}}Verify email matches input
$.passwordIs Null(Empty)Verify password is hidden
Once configured, run the request. If even one of these conditions is not met, Apidog will flag the test as failed.

Validating with Database Operations#

Response assertions are great, but they only tell you what the API says it did. Did the data actually arrive in the database?
Database Operations allow you to connect directly to your SQL database within a test step to verify the "ground truth."

Why you need this#

Data Integrity: The API says "User Created," but is the record actually in the users table?
State Validation: After a status update (e.g., "Order Paid"), is the database column updated correctly?
Data Cleanup: Delete test data after the test finishes.

How to use Database Operations#

1.
Configure Connection: Go to Settings -> Database Connections and add your MySQL/PostgreSQL/Oracle details.
2.
Add Post-processor: In your request, add Database Operation.
3.
Fill in the form:
Operation Name: e.g., "Verify User Created".
Database Connections: Select your pre-configured connection.
SQL Command: Enter your query. You can use variables!
Extract Result To Variable: Map the query result to a variable for future assertions.
Variable: db_user_id
JSONPath Expression: $[0].id (Extracts 'id' from the first row)
4.
Assert: Now you can add an assertion step to check if {{db_user_id}} matches the API response id.
Database Operation Config
See details: Database Operations

Advanced: Scripting with pm.dataSource#

For complex validation, you can use scripts to query and assert in one go.

Best Practices#

1.
Assert Everything: Every test step should have at least a status code assertion.
2.
Be Specific: Don't just check 200 OK. Check that the id is a number and the status is "active".
3.
Negative Testing: Create test cases that expect failure. E.g., send an invalid email and assert that the status code is 400 and the error message contains "Invalid email".
4.
Database Cleanliness: Use DB operations to DELETE the user created during testing at the end of your workflow (Teardown).

Key Takeaways#

Assertions are mandatory for reliable automation; without them, tests are blind.
Use Visual Assertions for 90% of your needs (status, body, headers).
Use Database Operations to verify data integrity and truly validate system state.
Combine API response checks with Database checks for Full-Stack QA.

What's Next#

We can now run a scenario and verify it works. But what if we need to run a test 100 times with different names? Or skip a step based on a condition?
In the next chapter, we'll introduce Flow Control and Looping to build logic into your tests.
Continue with → Flow Control: If, For, ForEach
Modified at 2025-12-25 09:53:19
Previous
Dynamic Values
Next
Flow Control: If, For, ForEach
Built with