# 6. Get results

<mark style="color:green;">`POST`</mark> `/getBatchResults`

This endpoint retrieves the results for a specific batch of documents. By providing the `extractionId` and `batchId`, you can obtain the processed data or the current status of the batch, indicating whether the processing is complete or still in progress. When also providing the `fileId`, the endpoint filters the results to only that file.

One alternative will be to use the [Webhook](/data-extraction-api/webhook.md) to receive the data when its ready on your own server.

## Postman Collection

For a complete and interactive set of API requests, please refer to our [Postman Integration](/data-extraction-api/postman-integration.md)collection.

## Server URL

```
https://api.extracta.ai/api/v1
```

## Headers

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <token>`   |

## Body

<table><thead><tr><th width="242">Name</th><th width="99">Type</th><th width="126">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>extractionId</code></td><td>string</td><td><code>true</code></td><td>The ID of the extraction</td></tr><tr><td><code>batchId</code></td><td>string</td><td><code>true</code></td><td>The ID of the batch</td></tr><tr><td><code>fileId</code></td><td>string</td><td><code>false</code></td><td>The ID of the file</td></tr></tbody></table>

## Body Example

```json
{
    "extractionId": "extractionId",
    "batchId": "batchId",
    "fileId": "fileId" // optional
}
```

## ⚠️ Important

To avoid rate-limiting, please ensure a delay of 2 seconds between consecutive requests to this endpoint.

## Code Example

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

/**
 * Retrieves the results for a specific batch of documents.
 * 
 * @param {string} token - The authorization token for API access.
 * @param {string} extractionId - The unique identifier for the extraction.
 * @param {string} batchId - The unique identifier for the batch.
 * @param {string} [fileId] - The unique identifier for the file (optional).
 * @returns {Promise<Object>} The promise that resolves to the batch results.
 */
async function getBatchResults(token, extractionId, batchId, fileId) {
    const url = "https://api.extracta.ai/api/v1/getBatchResults";

    try {
        // Constructing the request payload
        const payload = {
            extractionId,
            batchId
        };

        // Adding fileId to the payload if provided
        if (fileId) {
            payload.fileId = fileId;
        }

        const response = await axios.post(url, payload, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        });

        // Handling response
        return response.data; // Directly return the parsed JSON response
    } catch (error) {
        // Handling errors
        throw error.response ? error.response.data : new Error('An unknown error occurred');
    }
}

async function main() {
    const token = 'apiKey';
    const extractionId = 'extractionId';
    const batchId = 'batchId';
    const fileId = 'optionalFileId'; // Set this to null or undefined if you don't want to include it

    try {
        const batchResults = await getBatchResults(token, extractionId, batchId, fileId);
        console.log("Batch Results:", batchResults);
    } catch (error) {
        console.error("Failed to retrieve batch results:", error);
    }
}

main();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

def get_batch_results(token, extraction_id, batch_id, file_id=None):
    """
    Retrieves the results for a specific batch of documents.

    :param token: The authorization token for API access.
    :param extraction_id: The unique identifier for the extraction.
    :param batch_id: The unique identifier for the batch.
    :param file_id: The unique identifier for the file (optional).
    :return: The batch results as a Python dictionary.
    """
    url = "https://api.extracta.ai/api/v1/getBatchResults"
    
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {token}'
    }
    
    payload = {
        'extractionId': extraction_id,
        'batchId': batch_id
    }
    
    # Adding file_id to the payload if provided
    if file_id:
        payload['fileId'] = file_id

    response = requests.post(url, json=payload, headers=headers)
    
    # Check if the request was successful
    if response.status_code == 200:
        return response.json()  # Return the parsed JSON response
    else:
        # Handle errors or unsuccessful responses
        response.raise_for_status()

# Example usage
if __name__ == "__main__":
    token = 'apiKey'
    extractionId = 'extractionId'
    batchId = 'batchId'
    fileId = 'optionalFileId'  # Set this to None if you don't want to include it

    try:
        batch_results = get_batch_results(token, extractionId, batchId, fileId)
        print("Batch Results:", batch_results)
    except Exception as e:
        print("Failed to retrieve batch results:", e)

```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

/**
 * Retrieves the results for a specific batch of documents.
 * 
 * @param string $token The authorization token for API access.
 * @param string $extractionId The unique identifier for the extraction.
 * @param string $batchId The unique identifier for the batch.
 * @param string|null $fileId The unique identifier for the file (optional).
 * @return mixed The batch results or an error message.
 */
function getBatchResults($token, $extractionId, $batchId, $fileId = null) {
    $url = 'https://api.extracta.ai/api/v1/getBatchResults';

    // Initialize cURL session
    $ch = curl_init($url);
    
    // Prepare the payload
    $payload = [
        'extractionId' => $extractionId,
        'batchId' => $batchId
    ];

    // Adding fileId to the payload if provided
    if ($fileId !== null) {
        $payload['fileId'] = $fileId;
    }

    $payload = json_encode($payload);

    // Set cURL options
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $token,
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);

    try {
        // Execute cURL session
        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($ch)) {
            throw new Exception('Curl error: ' . curl_error($ch));
        }

        return $response;
    } catch (Exception $e) {
        // Handle exceptions or errors here
        return 'Error: ' . $e->getMessage();
    } finally {
        // Always close the cURL session
        curl_close($ch);
    }
}

// Example usage
$token = 'apiKey';
$extractionId = 'extractionId';
$batchId = 'batchId';
$fileId = 'optionalFileId'; // Set this to null if you don't want to include it

try {
    $batchResults = getBatchResults($token, $extractionId, $batchId, $fileId);
    echo $batchResults;
} catch (Exception $e) {
    echo "Failed to retrieve batch results: " . $e->getMessage();
}

?>
```

{% endtab %}
{% endtabs %}

## Responses

{% tabs %}
{% tab title="200 for all files" %}

```json
{
    "extractionId": "extractionId",
    "batchId": "batchId",
    "files": [
        {
            "fileName": "File 2.png",
            "status": "processed",
            "result": {
                "last_job_position": "Full-Stack Developer",
                "name": "John",
                "phone_number": "000 000 000",
                "surname": "Smith",
                "years_of_experience": "6"
            },
            "url": "fileUrl"
        },
        ...
    ]
}
```

{% endtab %}

{% tab title="200 for a single file" %}

```json
{
    "extractionId": "extractionId",
    "batchId": "batchId",
    "fileId": "fileId",
    "files": [
        {
            "fileName": "File 1.png",
            "status": "processed",
            "result": {
                "last_job_position": "Full-Stack Developer",
                "name": "John",
                "phone_number": "000 000 000",
                "surname": "Smith",
                "years_of_experience": "6"
            },
            "url": "fileUrl"
        }
    ]
}
```

{% endtab %}

{% tab title="200 status waiting" %}

```json
{
    "extractionId": "extractionId",
    "batchId": "batchId",
    "fileId": "fileId", // optional
    "status": "waiting"
}
```

{% endtab %}

{% tab title="400" %}

```json
{
    "error": "Invalid request"
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: 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:

```
GET https://docs.extracta.ai/data-extraction-api/api-endpoints-data-extraction/6.-get-results.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
