Where API Tests Belong in a CI/CD Pipeline With AI Agents
One of the most common problems I see in API test suites isn't bad test code. It's good test code running at the wrong moment. A team writes solid tests, wires them into CI/CD, and then wonders why the pipeline crawls or why a broken contract still slips through to staging. The tests are fine. The placement is wrong.
A pipeline isn't one slot you pour every test into. It's a sequence of gates, and each gate has a job. API tests are awkward because they span a wide range: some behave like unit tests, some need real infrastructure, and some are closer to end-to-end checks. Run them all in one stage and you get the worst of each.
Placement matters more now that coding agents open pull requests. When Copilot or another agent writes the change and the tests, the pipeline is the first reviewer that never gets tired. In this article I'll walk through which API tests belong in the pre-merge gate, which belong after deploy, where the slow contract and scenario suites go, and what I add to the pipeline so agent-authored changes can't quietly weaken it.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
The pre-merge gate: fast, isolated, contract-shaped
The pre-merge gate runs on every pull request before code lands on main. Its one hard constraint is speed. If developers wait too long for a PR check, they find ways around it. That makes me strict about what goes here. An API test earns a spot only if it meets all three of these:
- No live external dependency. Nothing that needs a shared database, a third-party service or a message broker. Use stubs or an in-process app instead.
- It checks contract and shape, not journeys. "POST /orders returns 201 with the right response fields" belongs here. A five-step checkout flow does not.
- The whole stage stays short. If the pre-merge API suite keeps growing, it's doing too much I/O or holding tests that belong later.
The simplest way to enforce this is a marker. In pytest you register it and select it in CI:
# pytest.ini
[pytest]
markers =
smoke: fast, dependency-free API tests safe for pre-merge
# CI command on pull requests
pytest -m smoke --tb=short
Behave works the same way: tag scenarios with @smoke and run behave --tags=smoke. The tooling is easy. The discipline of tagging correctly is the hard part, and I cover it in more depth in tagging API tests so CI can run the right subset.
Post-deploy verification: is this environment actually healthy?
Once a build is deployed to staging, the question changes. It's no longer "does this code look right?" but "did the deployment work, and does the API behave against real infrastructure?" A second, separate suite answers that.
- It runs against the deployed instance, so it catches configuration mistakes, missing environment variables and infrastructure problems that stubs never will.
- It covers critical happy paths: authentication, core reads and writes, and any integration the app can't function without.
- It's allowed to be slower than pre-merge, but it should still be time-boxed. Deeper scenarios go to a scheduled run.
I keep this suite in its own folder rather than relying on a tag, so a deployment script can't accidentally run the wrong set. The target comes from an environment variable read by a fixture, so the same suite points at staging today and production tomorrow:
# conftest.py in tests/verify/
import os
import pytest
@pytest.fixture(scope="session")
def base_url():
url = os.environ.get("API_BASE_URL")
if not url:
pytest.fail("API_BASE_URL is not set")
return url.rstrip("/")
# Deployment pipeline step
API_BASE_URL="$STAGING_URL" pytest tests/verify/ -v --tb=long
Failures here must block promotion. I've seen teams treat post-deploy failures as informational, a notification nobody reads while the build moves on anyway. That defeats the point. A non-zero exit code from pytest should stop the promotion step. This is also where request and response logging pays off, because you usually can't attach a debugger to a pipeline run. Status, headers and body in the test output let you diagnose from the artifact.
Contract and scenario suites: slow, valuable, scheduled
Some of the most useful API tests are also the slowest. Force them into a fast gate and they get disabled the first time the pipeline feels sluggish. Give them their own slot instead.
Contract tests catch changes that a schema check alone misses: a renamed field, a required property becoming optional, a new enum value consumers don't handle. They often need a running provider and sometimes a contract broker. Run them on every merge to main or nightly, and make them a required gate before a production release. I go deeper on this in API contract testing for breaking changes.
Multi-step scenario tests that exercise business logic across several endpoints belong in the same slot. Their signal is about system behaviour, not about whether this one commit broke something obvious.
| Stage | API test types | Trigger | Time budget |
|---|---|---|---|
| Pre-merge | Schema, stubbed integration, input validation | Every PR | Short |
| Post-deploy | Critical happy paths against real infrastructure | Every deploy | Moderate |
| Scheduled / release gate | Contract tests, full scenarios, regression | Merge to main, nightly, pre-release | Longest |
When agents open the pull requests
Coding agents change the economics of the pipeline. An agent can open many PRs a day, each with code and tests, and it will happily make a red build green. That's exactly what you asked for, unless the fastest route to green was weakening a test. So I add a few guards aimed at agent-authored changes.
- Protect the gate definitions. The CI workflow,
pytest.inimarkers and thetests/verify/folder should require a human review. A CODEOWNERS entry on those paths does this on GitHub. - Flag deleted or skipped tests. A cheap pre-merge step can fail when a PR adds
@pytest.mark.skip,xfailor removes a test function without a reviewer approving it. - Write the rules down for the agent. Copilot reads
.github/copilot-instructions.md, and most coding agents have an equivalent instructions file. Tell it which marker means what and that it must not move tests between stages to get a build passing.
## Pipeline rules for API tests
- tests marked smoke must not call real external services; use the stubs in tests/stubs/.
- Never add skip/xfail or remove a marker to get CI green. Explain the failure in the PR instead.
- tests/verify/ runs post-deploy against API_BASE_URL. Do not change it without asking.
If your product itself calls a model, there's a further wrinkle: those tests aren't deterministic. I keep them out of the pre-merge gate entirely, stub the model there, and run the real model-calling checks in the scheduled stage, judged by a pass rate over several runs rather than a single pass or fail.
Reliability before volume
None of this works if the tests are flaky. A flaky test in a deployment gate is worse than no test, because it teaches the team, and any agent watching CI, to retry until green. Invest in deterministic data setup, teardown that always runs and retries only where they're genuinely justified. If you're fighting that now, debugging a flaky API test that only fails in CI is a good place to start.
A small, reliable suite at the right stage beats a large, flaky one running everywhere. If you want to build that kind of suite from scratch with pytest or Behave, VS Code and GitHub Copilot, my API testing courses walk through it step by step.