> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://respan.ai/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://respan.ai/docs/_mcp/server.

# Cancel a batch

POST https://api.respan.ai/api/v1/batches/{batch_id}/cancel
Content-Type: application/json

Cancel an in-progress OpenAI-compatible batch. Already completed requests are not affected.

Reference: https://respan.ai/docs/apis/gateway/cancel-batch

## Authentication

- `Authorization` header (bearer token, required) — Use your Respan API key for Respan API authentication. Enter only the Respan API key value; clients send Authorization: Bearer \<RESPAN\_API\_KEY>. For /api/responses, provider credentials such as Perplexity, OpenAI, or Azure OpenAI go in Settings -> Providers or respan\_params.credential\_override in the request body, not in this authentication field.

## Request

### Path parameters

- `batch_id` (string, required) — Batch ID.

### Query parameters

- `provider_id` (string, required) — Provider route with customer-owned credentials, for example `openai` or `parasail`.

### Headers

- `X-Data-Respan-Params` (string, optional) — Base64-encoded JSON object of Respan request parameters. Legacy `X-Data-Keywordsai-Params` is still accepted.

## Response

### 200

Batch cancellation initiated.

- `id` (string, required) — Batch ID.
- `status` (enum, required)
  - Allowed values: `validating`, `pending`, `in_progress`, `finalizing`, `completed`, `failed`, `expired`, `cancelling`, `cancelled`
- `object` (string, optional)
- `endpoint` (string, optional)
- `input_file_id` (string, optional)
- `output_file_id` (string, optional, nullable) — Output file ID, available when the batch completes.
- `error_file_id` (string, optional, nullable) — Error file ID, when provider errors are available.
- `completion_window` (string, optional)
- `created_at` (integer, optional) — Unix timestamp.
- `in_progress_at` (integer, optional, nullable)
- `expires_at` (integer, optional, nullable)
- `finalizing_at` (integer, optional, nullable)
- `completed_at` (integer, optional, nullable)
- `failed_at` (integer, optional, nullable)
- `expired_at` (integer, optional, nullable)
- `cancelling_at` (integer, optional, nullable)
- `cancelled_at` (integer, optional, nullable)
- `request_counts` (ApiV1BatchesBatchIdCancelPostResponsesContentApplicationJsonSchemaRequestCounts, optional)
- `metadata` (map from string to any, optional)
- `errors` (any, optional, nullable) — Provider error details, when available.

## Errors

### 400 Bad Request Error

Bad Request

- `error` (string, optional)
- `detail` (string, optional)
- `error_class` (string, optional)
- `id` (string, optional)

### 401 Unauthorized Error

You haven't added your own key for the provider in Settings › Providers, or the provider rejected it. Files and batches always run on your own key; Respan credits can't cover them.

- `detail` (string, required)

### 403 Forbidden Error

The API key is missing, invalid or expired.

- `detail` (string, required)

### 404 Not Found Error

Not Found

- `error` (string, optional)
- `detail` (string, optional)
- `error_class` (string, optional)
- `id` (string, optional)

## Types

### ApiV1BatchesBatchIdCancelPostResponsesContentApplicationJsonSchemaRequestCounts

- `total` (integer, optional)
- `completed` (integer, optional)
- `failed` (integer, optional)

## Examples

**Request**

```json
{}
```

**Response**

```json
{
  "id": "batch_abc123",
  "status": "in_progress",
  "object": "batch",
  "endpoint": "/v1/chat/completions",
  "input_file_id": "file-abc123",
  "output_file_id": "string",
  "error_file_id": "string",
  "completion_window": "24h",
  "created_at": 1710000000,
  "in_progress_at": 1,
  "expires_at": 1,
  "finalizing_at": 1,
  "completed_at": 1,
  "failed_at": 1,
  "expired_at": 1,
  "cancelling_at": 1,
  "cancelled_at": 1,
  "request_counts": {
    "total": 100,
    "completed": 97,
    "failed": 3
  },
  "metadata": {},
  "errors": null
}
```

**SDK Code**

```python
import requests

url = "https://api.respan.ai/api/v1/batches/batch_abc123/cancel"

querystring = {"provider_id":"provider_id"}

payload = {}
headers = {
    "Authorization": "Bearer <respanApiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, params=querystring)

print(response.json())
```

```javascript
const url = 'https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <respanApiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <respanApiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <respanApiKey>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id")
  .header("Authorization", "Bearer <respanApiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id', [
  'body' => '{}',
  'headers' => [
    'Authorization' => 'Bearer <respanApiKey>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <respanApiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <respanApiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.respan.ai/api/v1/batches/batch_abc123/cancel?provider_id=provider_id")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```