> For the complete documentation index, see [llms.txt](https://learning.contextqa.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learning.contextqa.com/api-testing/creating-api-tests.md).

# Creating API Tests

## Quick answer

Step-by-step guide to creating API test cases in ContextQA — configuring requests, using variables, capturing responses, chaining calls, and importing from Swagger. Follow the documented prerequisites and steps, then verify the expected result before using the workflow in a shared or production process.

## What this page covers

{% hint style="info" %}
**Who is this for?** Developers and SDETs who want to create REST API test cases in ContextQA — including importing tests directly from a Swagger or OpenAPI specification.
{% endhint %}

This page walks through creating an API test case from scratch, wiring up variables, and generating tests from a Swagger specification.

[Watch the API test creation walkthrough](https://drive.google.com/file/d/1OyuSh20YojL-qkQs9-5rG2yYR4YqjQ98/preview).

## Creating an API test case

1. Open **Test Cases** and select **New Test Case**.
2. Choose **Create manually**, then select **Open step builder**.
3. Enter a test-case name, such as `API — Create user`, and select **Create Test Case**.
4. Open the new test's step builder and select **Add Test** (or the add-step action).
5. In **Create a New Step**, choose **API**. The API step opens on **Request Details**.

![Create a New Step dialog with API selected and the REST request details visible](/files/oLod36VAusC1JFey9MKU)

The panel exposes the following fields:

| Field          | Purpose                                                               |
| -------------- | --------------------------------------------------------------------- |
| HTTP method    | Select GET, POST, PUT, PATCH, or DELETE                               |
| URL            | The endpoint URL; environment values can supply the reusable base URL |
| Headers        | Key-value pairs; supports variable interpolation                      |
| Body           | JSON or other payload for POST/PUT/PATCH requests                     |
| Store response | Name of the variable that will hold the response                      |
| Validation     | Assertions to run against the response                                |

6. Select the HTTP method and enter the endpoint. For a JSON request, add `Content-Type: application/json`, open **Body**, select the JSON format, and enter a non-production payload.
7. Select **Send Request** to preview the response before saving. Use the preview to confirm the status and JSON structure.
8. Continue to **Store Response** and enter a variable name such as `result`. The response becomes available to later steps under that name.
9. Continue to **Validation** and add at least one status assertion, such as **status equals 200**.
10. Create the step, then select **Run** to execute the test.
11. Open **Run History** and inspect the request headers/body, response headers/body, and expected versus actual status.

{% hint style="info" %}
**Business use case:** Create an API test before the user interface is ready to verify that a service accepts the expected payload, returns the agreed status, and exposes the response fields the UI will depend on.
{% endhint %}

## Using variables in API requests

Variables prevent you from hard-coding sensitive values such as tokens, base URLs, or environment-specific hostnames directly into test steps.

### Defining a variable

1. Open your API test case.
2. Click the **variables** option in the test editor.
3. Enter a key (for example, `token`) and paste the value. Click **Create** to save it.

### Referencing a variable

Use the step editor's variable picker for local, global, and environment data. An environment variable such as `baseURL` is inserted as `*|baseURL|*`. Runtime response fields use `${variable.path}` syntax:

* **Authorization header from an earlier step:** `Bearer ${loginResult.body.token}`
* **URL with an environment variable:** `*|baseURL|*/api/v1/users`
* **Body field from an earlier step:** `"user_id": "${createUserResult.body.id}"`

Variable values are resolved at execution time. Use the picker whenever possible so ContextQA inserts the correct syntax and exact variable name.

### Variable scopes

* **Local variables** are defined at the test-case level and are available only within that test case.
* **Global variables** are available across all test cases in the workspace.
* **Runtime variables** are captured from API responses using the **Store response** field and are available to subsequent steps within the same execution.

## Sending the request and capturing the response

When you click **Send** in the API panel, ContextQA executes the request immediately and displays the response body, status code, and headers in the panel. Use this preview to:

* Confirm the JSON structure before writing JSON path assertions
* Copy the exact JSON path to a field (for example, `result.body.email`) for use in payload validation
* Verify that authentication headers are being resolved correctly from variables

After saving the step and running the test case, full response details are accessible in **Run History** under the **Response Body** tab.

## Chaining API calls

When one API step's response must feed into a later step, store the response in a named variable and reference its fields using dot notation.

**Example:** A `POST /auth` call stores its response as `result`. Double-click the token in the response preview to copy its JSON path, then set the next step's `Authorization` header to `Bearer ${result.body.access_token}` (adjust the path to match your response).

For a detailed walkthrough including hybrid API + UI chaining, see [API Chaining](/api-testing/api-chaining.md).

## Generating tests from a Swagger or OpenAPI specification

ContextQA can import a Swagger or OpenAPI file and produce a test case for each endpoint-and-status-code combination defined in the spec.

1. Click the **plus (+) icon** on the ContextQA dashboard.
2. Select **Import File**.
3. Choose **Import Requirement**, then select **API**.
4. Upload your `.json` or `.yaml` Swagger / OpenAPI file.
5. Review the imported endpoints and response codes in the preview panel.
6. Navigate to **Imported Files** and refresh the view to see the generated test cases.

Each generated test case reflects a documented endpoint and expected status code — for example, separate cases for `200`, `400`, `401`, and `500` responses on the same endpoint. You can then edit individual steps to add authentication headers, payloads, and more specific assertions.

This is also available through the `generate_tests_from_swagger` MCP tool, which accepts the same Swagger/OpenAPI content and produces the equivalent test cases programmatically.

{% hint style="info" %}
**Generate API tests from your Swagger spec in minutes.** [**Book a Demo →**](https://contextqa.com/book-a-demo/) — See ContextQA generate and execute REST API tests for your backend.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://learning.contextqa.com/api-testing/creating-api-tests.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
