### Install Behat API Context using Composer Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/install.md Installs the Behat API Context package as a development dependency using Composer. This is the primary method for adding the package to your project. If using Symfony Flex, the bundle will be automatically registered. ```bash composer require --dev macpaw/behat-api-context ``` -------------------------------- ### Optional: Configure Custom Reset Manager for Behat API Context Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/install.md Provides an example of how to manually override the Behat API Context configuration to specify a custom reset manager. This is useful for advanced scenarios where default reset behavior needs to be customized. ```yaml # config/packages/behat_api_context.yaml when@test: behat_api_context: kernel_reset_managers: - BehatApiContext\Service\ResetManager\DoctrineResetManager ``` -------------------------------- ### JSON with Dynamic Date Parameter Example Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/runnable-parameters.md Illustrates mixing static JSON data with dynamic PHP expressions for parameter generation. This example shows setting a static 'start_date' and a dynamic 'end_date' calculated using PHP's DateTimeImmutable. ```json { "start_date": "2024-01-01", "end_date": "<(new DateTimeImmutable('+7 days'))->format('Y-m-d')>" } ``` -------------------------------- ### Configure Behat with ApiContext Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/install.md Sets up the Behat configuration file to include the ApiContext. This allows Behat to use the API testing capabilities provided by the context. ```yaml # behat.yml default: suites: default: contexts: - BehatApiContext\Context\ApiContext ``` -------------------------------- ### Gherkin: Successful Login API Test Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/examples.md Demonstrates a successful login scenario using the API Context. It defines request parameters, sends a POST request to the sign-in route, and asserts a 200 status code with a valid token in the response. ```gherkin Feature: Login API Scenario: Successful login returns token Given the request contains params: """ { "email": "test@example.com", "password": "securepassword" } """ When I send "POST" request to "api_v1_sign_in" route Then response status code should be 200 And response should be JSON with variable fields "token": """ { "token": "abc123" } """ ``` -------------------------------- ### Gherkin: Relative Dates in API Request Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/examples.md Shows how to use relative dates within API request parameters. This example dynamically sets 'dateFrom' to 7 days ago and 'dateTo' to the current date for generating reports, expecting a 201 status code. ```gherkin Scenario: Create report with dynamic date range Given the request contains params: """ { "dateFrom": "<(new DateTimeImmutable('-7 days'))->format('Y-m-d')>", "dateTo": "<(new DateTimeImmutable())->format('Y-m-d')>" } """ When I send a "POST" request to "api_v1_generate_reports" Then response status code should be 201 ``` -------------------------------- ### Register BehatApiContextBundle Manually in Symfony Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/install.md Registers the Behat API Context Bundle manually in Symfony applications that do not use Symfony Flex. This ensures the bundle is recognized and its services are available for testing. ```php // config/bundles.php return [ BehatApiContext\BehatApiContextBundle::class => ['test' => true], ]; ``` -------------------------------- ### Send HTTP Requests to Symfony Routes Source: https://context7.com/macpaw/behat-api-context/llms.txt Send HTTP requests to defined Symfony routes with custom headers and parameters. Supports various HTTP methods like GET, POST, and PATCH. The input includes the HTTP method, the route name, and optional request parameters or headers. ```gherkin Feature: Product API Scenario: Get product list When I send "GET" request to "api_products_list" route Then response status code should be 200 And response is JSON Scenario: Create new product Given the "Authorization" request header contains "Bearer admin_token" And the request contains params: """ { "name": "Laptop", "price": 999.99, "category": "electronics", "stock": 50 } """ When I send "POST" request to "api_products_create" route Then response status code should be 201 And response should be JSON with variable fields "id": """ { "id": 1, "name": "Laptop", "price": 999.99, "category": "electronics", "stock": 50 } """ Scenario: Update product with route parameters Given the request contains params: """ { "id": 42, "price": 899.99, "stock": 45 } """ When I send "PATCH" request to "api_products_update" route Then response status code should be 200 ``` -------------------------------- ### Configure Custom Reset Managers for Behat API Context Source: https://context7.com/macpaw/behat-api-context/llms.txt Optionally, configure custom reset managers for the Behat API Context in your Symfony application. This allows for specific cleanup or setup procedures between test scenarios, such as resetting the database using Doctrine. ```yaml # config/packages/behat_api_context.yaml - Optional: Add custom reset managers when@test: behat_api_context: kernel_reset_managers: - BehatApiContext\Service\ResetManager\DoctrineResetManager ``` -------------------------------- ### Gherkin: Invalid Credentials API Test Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/examples.md Illustrates a login scenario with invalid credentials. It sends a POST request to the sign-in route with incorrect password details and verifies that the response status code is 401 (Unauthorized) with an "Invalid credentials" error message. ```gherkin Scenario: Login with wrong password Given the request contains params: """ { "email": "test@example.com", "password": "wrongpassword" } """ When I send "POST" request to "api_v1_sign_in" route Then response status code should be 401 And response should be JSON: """ { "error": "Invalid credentials" } """ ``` -------------------------------- ### Compare JSON Response (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Compares the actual JSON response received from the API with a predefined expected JSON structure for exact equality. This step requires the expected JSON to be provided directly. ```gherkin Then response should be JSON: """ { "success": true, "data": { "id": 123 } } """ ``` -------------------------------- ### E-commerce Workflow with Behat API Context (Gherkin) Source: https://context7.com/macpaw/behat-api-context/llms.txt A comprehensive Gherkin feature file that defines a multi-step e-commerce workflow. This includes user registration, login, order creation, and order status verification, demonstrating the use of dynamic parameters, authentication, and data saving across multiple API calls. ```gherkin Feature: Complete E-commerce Workflow Scenario: User registers, logs in, creates order, and checks status # Step 1: Register new user Given the request contains params: """ { "email": "customer@example.com", "password": "SecurePass123", "name": "Jane Customer", "registered_at": "<(new DateTimeImmutable())->format('Y-m-d H:i:s')>" } """ When I send "POST" request to "api_register" route Then response status code should be 201 And I save "user.id" param from json response as "userId" # Step 2: Login with created account Given the request contains params: """ { "email": "customer@example.com", "password": "SecurePass123" } """ When I send "POST" request to "api_login" route Then response status code should be 200 And I save "token" param from json response as "authToken" # Step 3: Create an order with authenticated user Given the "Authorization" request header contains "Bearer {{authToken}}" And the request contains params: """ { "user_id": "{{userId}}", "items": [ { "product_id": 101, "quantity": 2, "price": 49.99 } ], "total": 99.98, "order_date": "<(new DateTimeImmutable())->format('Y-m-d')>" } """ When I send "POST" request to "api_orders_create" route Then response status code should be 201 And response should be JSON with variable fields "order_id, created_at": """ { "order_id": 12345, "user_id": "{{userId}}", "status": "pending", "total": 99.98, "created_at": "2024-01-15T10:30:00Z" } """ And I save "order_id" param from json response as "orderId" # Step 4: Check order status Given the "Authorization" request header contains "Bearer {{authToken}}" And the request contains params: """ { "order_id": "{{orderId}}" } """ When I send "GET" request to "api_orders_status" route Then response status code should be 200 And the "X-Order-ID" response headers contains "{{orderId}}" And response should be JSON: """ { "order_id": "{{orderId}}", "status": "pending", "user_id": "{{userId}}" } """ ``` -------------------------------- ### Register Behat API Context Bundle in Symfony Source: https://context7.com/macpaw/behat-api-context/llms.txt Register the Behat API Context Bundle within your Symfony project's configuration. This ensures that the bundle's services and features are available during testing. Registration is typically automatic when using Symfony Flex. ```php // config/bundles.php - Register the bundle (automatic with Flex) return [ BehatApiContext\BehatApiContextBundle::class => ['test' => true], ]; ``` -------------------------------- ### Configure Behat to Use API Context Source: https://context7.com/macpaw/behat-api-context/llms.txt Configure Behat to utilize the API context by specifying the ApiContext class in your behat.yml configuration file. This step is crucial for enabling the BDD API testing features. ```yaml # behat.yml - Configure Behat to use the API context default: suites: default: contexts: - BehatApiContext\Context\ApiContext ``` -------------------------------- ### Save JSON Response Param (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Extracts a specific parameter from the JSON response using a dot-notated path and saves its value into the test context under a given key. This enables the use of response data in subsequent steps. ```gherkin When I save "data.id" param from json response as "userId" ``` -------------------------------- ### Add Request Parameters (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Adds parameters to the request payload or query string. It supports embedded PHP expressions for dynamic values and saves parameters for subsequent use in the test context. ```gherkin Given the request contains params: """ { "user_id": "", "active": true } """ ``` -------------------------------- ### Assert Response is Empty (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Confirms that the HTTP response body is empty. This assertion is useful for testing endpoints that are expected to return no content. ```gherkin Then response should be empty ``` -------------------------------- ### Set Request Headers for API Requests (Gherkin) Source: https://context7.com/macpaw/behat-api-context/llms.txt Define HTTP headers for API requests using Gherkin syntax. Supports static values and dynamic values extracted from previous responses, enabling authentication and content type specification. ```gherkin Feature: Authentication API Scenario: Access protected endpoint with bearer token Given the "Authorization" request header contains "Bearer abc123token" And the "Content-Type" request header contains "application/json" When I send "GET" request to "api_user_profile" route Then response status code should be 200 ``` ```gherkin Scenario: Multi-line header with dynamic values # First get a token Given the request contains params: """ { "username": "admin", "password": "secret" } """ When I send "POST" request to "api_login" route And I save "token" param from json response as "auth_token" # Use the token in a multiline header Given the "Authorization" request header contains multiline value: """ Bearer {{auth_token}} X-User-Id=12345 """ When I send "GET" request to "api_admin_dashboard" route Then response status code should be 200 ``` -------------------------------- ### Add Request Parameters with Dynamic Data (Gherkin) Source: https://context7.com/macpaw/behat-api-context/llms.txt Add JSON payload or query parameters to API requests using Gherkin steps. Supports dynamic data generation through PHP expressions and variable substitution for flexible request bodies. ```gherkin Feature: User Registration Scenario: Register new user with dynamic data Given the request contains params: """ { "email": "user@example.com", "password": "SecurePass123", "username": "johndoe", "registered_at": "<(new DateTimeImmutable())->format('Y-m-d H:i:s')>", "user_id": "", "agreement_accepted": true } """ When I send "POST" request to "api_user_register" route Then response status code should be 201 And response should be JSON with variable fields "id, created_at": """ { "id": 12345, "email": "user@example.com", "username": "johndoe", "created_at": "2024-01-15 10:30:00" } """ ``` ```gherkin Scenario: Create report with relative date range Given the request contains params: """ { "report_type": "sales", "date_from": "<(new DateTimeImmutable('-7 days'))->format('Y-m-d')>", "date_to": "<(new DateTimeImmutable())->format('Y-m-d')>", "format": "pdf" } """ When I send "POST" request to "api_generate_report" route Then response status code should be 201 ``` -------------------------------- ### PHP Expressions in Gherkin Request Payload Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/runnable-parameters.md Demonstrates how to embed inline PHP expressions within a Gherkin `Given` step for API request payloads. These expressions are evaluated by Behat API Context to generate dynamic values. Ensure expressions do not return null and do not use return statements or semicolons. ```gherkin Given the request contains params: """ { "timestamp": "<(new DateTimeImmutable())->getTimestamp()>", "uuid": "" } """ ``` -------------------------------- ### Exact JSON Response Matching Source: https://context7.com/macpaw/behat-api-context/llms.txt Compare the JSON response from an API call with a predefined JSON structure for exact equality. This is useful for validating specific response payloads, such as login tokens or error messages. ```gherkin Feature: Exact JSON Validation Scenario: Login returns expected token structure Given the request contains params: """ { "email": "test@example.com", "password": "password123" } """ When I send "POST" request to "api_login" route Then response status code should be 200 And response should be JSON: """ { "success": true, "token": "abc123xyz789", "expires_in": 3600 } """ Scenario: Error response validation Given the request contains params: """ { "email": "invalid", "password": "wrong" } """ When I send "POST" request to "api_login" route Then response status code should be 401 And response should be JSON: """ { "success": false, "error": "Invalid credentials" } """ ``` -------------------------------- ### Set Request Header (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Sets or replaces a specified HTTP request header with a given value. Supports variable substitutions. This step is part of the API testing context for Behat. ```gherkin Given the "Authorization" request header contains "Bearer abc123" ``` -------------------------------- ### Send HTTP Request (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Sends an HTTP request using a specified method (e.g., POST) to a named Symfony route. It utilizes previously configured headers and parameters. ```gherkin When I send "POST" request to "api_login" route ``` -------------------------------- ### Dynamic Response Validation API Source: https://context7.com/macpaw/behat-api-context/llms.txt This section covers the dynamic response validation capabilities, allowing for flexible JSON comparisons where specific fields can vary or match predefined patterns. ```APIDOC ## POST api_users_create ### Description Validates the response structure for a user creation request, allowing specific fields like 'id', 'createdAt', and 'updatedAt' to vary. ### Method POST ### Endpoint api_users_create ### Parameters #### Request Body - **email** (string) - Required - The email of the user. - **name** (string) - Required - The name of the user. ### Request Example ```json { "email": "test@example.com", "name": "Alice Smith" } ``` ### Response #### Success Response (201) - **id** (any) - The unique identifier for the created user (can vary). - **email** (string) - The email of the user. - **name** (string) - The name of the user. - **createdAt** (string) - The timestamp when the user was created (can vary). - **updatedAt** (string) - The timestamp when the user was last updated (can vary). - **status** (string) - The current status of the user. #### Response Example ```json { "id": 999, "email": "test@example.com", "name": "Alice Smith", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z", "status": "active" } ``` ## POST api_orders_create ### Description Validates the response structure for an order creation request, allowing specific fields like 'orderId', 'createdAt', and 'token' to match regular expression patterns. ### Method POST ### Endpoint api_orders_create ### Response #### Success Response (201) - **orderId** (string) - A UUID pattern for the order ID (can vary). - **status** (string) - The status of the order. - **total** (number) - The total amount of the order. - **createdAt** (string) - A timestamp pattern (e.g., Unix epoch) for creation time (can vary). - **token** (string) - A pattern for the authentication token (can vary). #### Response Example ```json { "orderId": "~^[0-9a-fA-F]{8}\"-\"[0-9a-fA-F]{4}\"-\"[0-9a-fA-F]{4}\"-\"[0-9a-fA-F]{4}\"-\"[0-9a-fA-F]{12}$", "status": "pending", "total": 299.99, "createdAt": "~^\\d{10}$", "token": "~^[a-zA-Z0-9]{32}$" } ``` ## POST api_cart_add ### Description Performs partial validation on a cart add request response, allowing fields like 'cart_id', 'updated_at', and 'session_token' to vary. ### Method POST ### Endpoint api_cart_add ### Parameters #### Request Body - **product_id** (integer) - Required - The ID of the product to add to the cart. ### Request Example ```json { "product_id": 123 } ``` ### Response #### Success Response - **cart_id** (any) - The ID of the shopping cart (can vary). - **items_count** (integer) - The number of items in the cart. - **total** (number) - The total cost of items in the cart. - **updated_at** (string) - The timestamp of the last update (can vary). - **session_token** (string) - The session token (can vary). #### Response Example ```json { "cart_id": 456, "items_count": 1, "total": 99.99, "updated_at": "2024-01-15 10:30:00", "session_token": "random_token_here" } ``` ``` -------------------------------- ### Configure Request IP Address for API Testing (Gherkin) Source: https://context7.com/macpaw/behat-api-context/llms.txt Set the client IP address for outgoing API requests using Gherkin steps. This is useful for testing IP-based access control and restrictions on your API endpoints. ```gherkin Feature: IP-based Access Control Scenario: Access from whitelisted IP Given the request ip is "192.168.1.100" And the "Authorization" request header contains "Bearer token123" When I send "GET" request to "api_admin_endpoint" route Then response status code should be 200 And response should be JSON: """ { "status": "success", "message": "Access granted" } """ Scenario: Access from blocked IP Given the request ip is "10.0.0.1" When I send "GET" request to "api_admin_endpoint" route Then response status code should be 403 ``` -------------------------------- ### Assert Response is JSON (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Checks if the response body contains valid and non-empty JSON data. This step is often used as a preliminary check before further JSON content assertions. ```gherkin Then response is JSON ``` -------------------------------- ### Assert JSON Response with Variable Fields (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Compares the actual JSON response to the expected JSON, allowing specified fields to be ignored or matched using regular expressions. This is useful for handling dynamic values like timestamps or UUIDs. ```gherkin Then response should be JSON with variable fields "id, createdAt, updatedAt": """ { "user": { "id": "~^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$", "name": "John", "createdAt": "~^\\d+$", "updatedAt": "~^\\d+$" } } """ ``` -------------------------------- ### Assert Response Status Code (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Verifies that the HTTP response status code matches the expected integer value. This is a fundamental assertion for API testing. ```gherkin Then response status code should be 200 ``` -------------------------------- ### Set Multiline Request Header (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Sets a request header with a multiline value, allowing for more complex header content such as authentication tokens or key-value pairs. This is useful for headers requiring specific formatting. ```gherkin Given the "Authorization" request header contains multiline value: """ Bearer {{token}} UserId={{user_id}} """ ``` -------------------------------- ### Response Header Validation API Source: https://context7.com/macpaw/behat-api-context/llms.txt This section details how to validate response headers, ensuring they contain expected values for various scenarios including content type, custom headers, and CORS policies. ```APIDOC ## GET api_products_list ### Description Verifies that the 'Content-Type' response header is set to 'application/json'. ### Method GET ### Endpoint api_products_list ### Response #### Success Response (200) - **Content-Type** (string) - Must contain 'application/json'. ## GET api_protected_resource ### Description Validates custom response headers, specifically 'X-Rate-Limit-Remaining' and 'X-Request-ID', after authenticating with a provided API key. ### Method GET ### Endpoint api_protected_resource ### Parameters #### Request Header - **X-API-Key** (string) - Required - The API key for authentication. ### Response #### Success Response (200) - **X-Rate-Limit-Remaining** (string) - The number of remaining requests allowed. - **X-Request-ID** (string) - A unique identifier for the request, typically prefixed with 'req-'. ## GET api_public_data ### Description Checks for the presence and correct value of the 'Access-Control-Allow-Origin' CORS header when a specific 'Origin' header is provided in the request. ### Method GET ### Endpoint api_public_data ### Parameters #### Request Header - **Origin** (string) - Required - The origin domain requesting the resource. ### Response #### Success Response (200) - **Access-Control-Allow-Origin** (string) - The allowed origin, which should match the request's 'Origin' header. ``` -------------------------------- ### Assert Response Header Contains Substring (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Asserts that a specific response header contains a given substring. This is useful for verifying content types or other header values that might have additional parameters. ```gherkin Then the "Content-Type" response headers contains "application/json" ``` -------------------------------- ### Set Request IP Address (Gherkin) Source: https://github.com/macpaw/behat-api-context/blob/develop/docs/steps.md Specifies the client IP address for an outgoing request by modifying the `REMOTE_ADDR` server parameter. This is useful for simulating requests from specific IP addresses. ```gherkin Given the request ip is "192.168.1.1" ``` -------------------------------- ### Validate HTTP Response Status Code Source: https://context7.com/macpaw/behat-api-context/llms.txt Assert the HTTP status code of an API response. This is useful for verifying the success or failure of requests, such as successful retrieval (200), creation (201), unauthorized access (401), or resource not found (404). ```gherkin Feature: API Status Validation Scenario: Successful request When I send "GET" request to "api_health_check" route Then response status code should be 200 Scenario: Unauthorized access When I send "GET" request to "api_admin_users" route Then response status code should be 401 Scenario: Not found Given the request contains params: """ { "id": 99999 } """ When I send "GET" request to "api_user_detail" route Then response status code should be 404 ``` -------------------------------- ### Validate JSON Response Content Source: https://context7.com/macpaw/behat-api-context/llms.txt Verify that an API response contains valid, non-empty JSON. This step ensures that the response body is correctly formatted as JSON, which is crucial for applications relying on JSON data exchange. ```gherkin Feature: JSON Response Validation Scenario: API returns valid JSON When I send "GET" request to "api_status" route Then response status code should be 200 And response is JSON Scenario: JSON structure validation Given the request contains params: """ { "query": "test" } """ When I send "POST" request to "api_search" route Then response is JSON ``` -------------------------------- ### Save Values from JSON Response Source: https://context7.com/macpaw/behat-api-context/llms.txt Extract specific values from a JSON API response and save them as variables for use in subsequent steps or scenarios. This enables multi-step workflows where data from one API call influences another. ```gherkin Feature: Multi-step User Workflow Scenario: Create user and then fetch their profile # Step 1: Create user Given the request contains params: """ { "email": "newuser@example.com", "name": "John Doe" } """ When I send "POST" request to "api_users_create" route Then response status code should be 201 And I save "data.id" param from json response as "userId" And I save "data.email" param from json response as "userEmail" # Step 2: Fetch the created user's profile using saved ID Given the request contains params: """ { "id": "{{userId}}" } """ When I send "GET" request to "api_user_profile" route Then response status code should be 200 And response should be JSON: """ { "id": "{{userId}}", "email": "{{userEmail}}", "name": "John Doe" } """ Scenario: Nested value extraction When I send "GET" request to "api_user_details" route And I save "user.profile.settings.theme" param from json response as "userTheme" Then response status code should be 200 ``` -------------------------------- ### Validate Empty API Response Source: https://context7.com/macpaw/behat-api-context/llms.txt Assert that the response body of an API call is empty. This is commonly used for operations like DELETE requests that signify success by returning no content (e.g., status code 204). ```gherkin Feature: Empty Response Validation Scenario: Delete returns no content Given the "Authorization" request header contains "Bearer admin_token" And the request contains params: """ { "id": 123 } """ When I send "DELETE" request to "api_user_delete" route Then response status code should be 204 And response should be empty ``` -------------------------------- ### Response Header Validation in Gherkin Source: https://context7.com/macpaw/behat-api-context/llms.txt Asserts that specific response headers contain expected values or patterns. This is crucial for verifying content types, security tokens, rate limits, and CORS policies. ```gherkin Feature: Response Header Validation Scenario: Verify content type header When I send "GET" request to "api_products_list" route Then response status code should be 200 And the "Content-Type" response headers contains "application/json" Scenario: Check custom headers Given the "X-API-Key" request header contains "secret123" When I send "GET" request to "api_protected_resource" route Then response status code should be 200 And the "X-Rate-Limit-Remaining" response headers contains "99" And the "X-Request-ID" response headers contains "req-" Scenario: CORS header validation Given the "Origin" request header contains "https://example.com" When I send "GET" request to "api_public_data" route Then response status code should be 200 And the "Access-Control-Allow-Origin" response headers contains "https://example.com" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.