> 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

Create ContextQA API tests manually, import a cURL command, reuse variables, capture responses, chain requests, or generate coverage from OpenAPI.

## Quick answer

Create an API step manually or use **Import API cURL** to populate its method, URL, headers, payload, authorization mode, and redirect behavior. Review imported values, replace secrets and environment-specific hosts with ContextQA variables, preview the request, add response validations, and run the saved test. Use Swagger or OpenAPI import when you need broader endpoint-and-status coverage instead of a single request.

## 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).

## Interactive demo: create and execute an API test

Follow this guided workflow to configure an API request, add validation, execute the test, and inspect the result without accessing a live workspace.

{% embed url="<https://app.storylane.io/share/gsrevxyu2zch>" %}

### What to notice

* The request method, endpoint, headers, payload, and expected response remain reviewable before execution.
* A saved response can supply values to later API or UI steps.
* Execution results connect the request, response, and validation outcome for faster investigation.

## 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](https://4255556216-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKlyaXxb76z3Dn47TrZkU%2Fuploads%2Fgit-blob-1450e3e96dbcf5ad7ffa36b3c42b405bdefd8a05%2Fcontextqa-api-rest-step-builder.jpg?alt=media)

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 %}

## Import an API request from cURL

Use cURL import when a developer, API client, browser network inspector, or service runbook already provides a working request.

1. Create or edit an **API** step.
2. On **Request Details**, select **Import API cURL**.
3. Paste one complete cURL command into **Paste your cURL command**.
4. Select **Import**.
5. Review the populated method, URL, headers, payload, authorization mode, and redirect setting.
6. Replace environment-specific hosts, tokens, cookies, and other secrets with approved ContextQA variables.
7. Select **Send Request** and verify the response before saving the step.
8. Add status, schema, or payload validation and run the saved test case.

{% hint style="warning" %}
A copied cURL command can contain bearer tokens, cookies, API keys, personal data, or production endpoints. Remove or parameterize sensitive values before saving the step, and use a non-production target unless the test has explicit production approval.
{% endhint %}

The import converts the request into editable ContextQA fields; it does not make the source command authoritative. Confirm any shell escaping, encoded body, repeated header, file upload, or authentication detail after conversion.

## 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.

Variables can also parameterize supported request-payload keys as well as values. This is useful when the contract uses an environment-specific property name. Keep the resulting JSON valid after substitution, preview it with **Send Request**, and prefer a fixed schema when the API contract does not intentionally vary.

### 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 supported Swagger or OpenAPI file and generate candidate API tests. Review the saved cases against the operations and outcomes you need; the import does not guarantee one case for every endpoint-and-status combination.

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.

Inspect each candidate’s request and expected response. Add authentication, valid and invalid fixtures, relevant status assertions, business values, and cleanup. Use your API contract to decide whether a denied request should return `401`, `403`, or another documented outcome; do not copy status expectations blindly.

The `generate_tests_from_swagger` MCP tool accepts `file_path_or_url`. Inspect its current authenticated schema and supported input. A hosted server cannot automatically read a laptop path: use an approved service-accessible source or supported upload. Generation and execution are separate evidence steps. Follow the [OpenAPI contract-testing guide](/testing-with-ai-coding-agents/openapi-contract-testing.md) to review scope and assertions before a run.

## Related documentation

* [Validate API responses](/api-testing/validating-responses.md)
* [Chain API calls](/api-testing/api-chaining.md)
* [Use variables and environments](/execution/environments.md)
* [Run your first API test](/api-testing/api-testing-tutorial.md)

{% hint style="info" %}
**Review generated API tests against your backend’s requirements.** [**Book a Demo →**](https://contextqa.com/book-a-demo/?utm_source=learning.contextqa.com\&utm_medium=referral\&utm_campaign=docs_demand_gen\&utm_content=creating-api-tests) — 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
