zrizDocsLearnSecuritySign inSign up

Test that a missing record returns 404

Ask for a record that does not exist in a zriz pipeline. The API must answer 404 with an error, not 500 and not 200 with an empty body.

Lesson 10 of 10 · zz 0.8.0 or later · Updated · Plain text for agents: /learn/test-api-404-not-found.md

The problem

A request for an unknown id shows how an API handles nothing. Some APIs answer 500, because the code reads a field of a null record. Others answer 200 with an empty body, and the client breaks later.

The test

The example is a shop API. GET /api/orders/{order-id} gives one order. The test asks for an id that no order has.

Start from a project that zz init made: the quick start gives the commands. Add two actions to the resource file.

.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" },
    "get-order": { "method": "GET", "path": "/api/orders/{order-id}" }
  }
}

.zriz/pipelines/order-not-found.json:

{
  "description": "An unknown order id must get 404",
  "steps": [
    {
      "call": "target/register",
      "body": { "email": "u-${gen.uuid}@test.com", "password": "secret123", "name": "Ann" },
      "expect": [["status", "==", 201]],
      "save": { "token": "body.token" }
    },
    { "set": { "order-id": "${gen.uuid}" } },
    {
      "call": "target/get-order",
      "headers": { "Authorization": "Bearer ${ctx.token}" },
      "expect": [
        ["status", "==", 404],
        ["body.error", "==", "order not found"],
        ["body.order_id", "not-exists"]
      ]
    }
  ]
}

Run it

zz run order-not-found
"status":"pass"

What it proves

Common mistake: A test with no token gets 401 and never reaches the code that looks for the record.

Next