# Testing API requests

When testing HTTP requests you need to create mock responses based on what would actually be returned from a real HTTP request. Symfony's HTTPClient has support for [testing HTTP requests](https://symfony.com/doc/current/http_client.html#http-client-and-responses).

You can also use the`MockResponseFromFile` class to generate a mock response easily from a file.

## MockResponseFromFile

Allows you to load a mock request from file.

### Parameters

* `$filename (string)` File to load mock response from

### Description

Body file is loaded from `{$filename}`

The optional info file is loaded from `{$filename}.info.php` and must contain the `$info` variable (array). By default mock responses return a 200 status code which you can change by setting the `$info` array.

### Usage

The following code loads `./responses/api-test.json` and if it exists `./responses/api-test.json.info.php` to create a mock response.

```php
use Symfony\Component\HttpClient\MockHttpClient;
use Strata\Data\Api_DELETE\RestApi;
use Strata\Data\Response\MockResponseFromFile;

$responses = [
    new MockResponseFromFile(__DIR__ . '/responses/api-test.json'),
];

$api = new RestApi('https://example.com/');
$api->setClient(new MockHttpClient($responses, 'https://example.com/'));

$response = $api->get('test');

// Outputs:404
echo $response->getStatusCode();

// Outputs: JSON response content
echo $response->getContent();

// Outputs: 0
echo $api->getHeader($response, 'X-Total-Results');
```

#### ./responses/api-test.json

```javascript
{
  "message": "PAGE NOT FOUND"
}
```

#### ./responses/api-test.json.info.php

```php
<?php
$info = [
    'http_code' => 404,
    'response_headers' => [
        'X-Total-Results' => '0'
    ]
];
```

See [ResponseInterface::getInfo()](https://github.com/symfony/symfony/blob/master/src/Symfony/Contracts/HttpClient/ResponseInterface.php) for possible info, the most common are:

* `http_code (int)` - the last HTTP response code
* `response_headers (array)` - an array of response headers


---

# 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.strata.dev/data/advanced-usage/testing-api-requests.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.
