zrizDocsLearnSecuritySign inSign up

Test an API status code and response body

Check the status code and the fields of the result in one zriz pipeline. A test that reads only the status code misses a wrong body.

Lesson 1 of 10 · zz 0.8.0 or later · Updated · Plain text for agents: /learn/test-api-status-code-and-body.md

The problem

An API can answer 201 and send a wrong body. A field is absent, or it holds the data of a different user. A test that reads only the status code passes, and the client breaks.

The test

The example is a shop API. POST /api/auth/register makes a user and answers 201 with a token.

Start from a project that zz init made: the quick start gives the commands. Add the action register to the resource file. Keep the action check as it is.

.zriz/resources/target.json:

{
  "type": "http",
  "description": "Your app under test",
  "base-url": "${env.TARGET_URL}",
  "headers": { "Content-Type": "application/json" },
  "actions": {
    "check": { "method": "GET", "path": "/api/health" },
    "register": { "method": "POST", "path": "/api/auth/register" }
  }
}

.zriz/pipelines/register-reply.json:

{
  "description": "Sign up: check the status code and the body",
  "steps": [
    { "set": { "email": "u-${gen.uuid}@test.com" } },
    {
      "call": "target/register",
      "body": { "email": "${ctx.email}", "password": "secret123", "name": "Ann" },
      "expect": [
        ["status", "==", 201],
        ["body.email", "==", "${ctx.email}"],
        ["body.name", "==", "Ann"],
        ["body.user_id", "not-empty"],
        ["body.token", "not-empty"]
      ]
    }
  ]
}

Run it

zz run register-reply
"status":"pass"

What it proves

Common mistake: A fixed e-mail passes one time, then fails as a duplicate. ${gen.uuid} makes a new e-mail for each run.

Next