Testing REST and GraphQL in PHPStorm: HTTP Client, Environments and Variables
AI generated
IDE
{ }
PHPStorm · HTTP Client · REST · GraphQL · Magento
Testing REST and GraphQL in PHPStorm
HTTP Client, Environments and Variables

The PHPStorm HTTP Client fully replaces Postman for many developers: .http files versioned in the repo, environments for dev/staging/prod, variables for tokens and IDs, response handlers for automatic assertions. For Magento REST and GraphQL there are specific patterns that make testing considerably easier.

16 min read .http files · Environments · Variables · Response handlers PHPStorm 2024+ · Magento 2.4 · REST · GraphQL

1. PHPStorm HTTP Client: overview and strengths

The HTTP Client built into PHPStorm has been available since version 2017.3 and has since evolved into a full-fledged API testing tool. Unlike external tools such as Postman or Insomnia, the HTTP Client is integrated directly into the IDE: requests are stored as plain text in .http files, which can be checked into Git. That makes API tests part of the repository, with versioning, code review and team access.

The main strengths of the PHPStorm HTTP Client are: syntax highlighting and autocomplete for HTTP methods, headers and JSON bodies. Environment files for different target environments without changing the actual request files. Variable extraction from responses that can be used in follow-up requests. JavaScript-based response handlers for automatic assertions. For Magento development this means testing REST endpoints and GraphQL directly from PHPStorm without ever leaving the IDE.

2. .http files: syntax and structure

An .http file contains one or more HTTP requests, separated by ###. Each request starts with the HTTP method, URL and optional headers, followed by an optional body after a blank line. PHPStorm shows a "Run" button above every request, which lets you execute the request directly. The response appears in its own tool window with syntax highlighting, status code and all response headers.

A file can contain any number of requests and is usually organized by topic: one file per API area or feature. For Magento you could create magento-catalog.http for catalog endpoints and magento-customer.http for customer endpoints. All these files are checked into Git, either under tests/api/ or directly in the project root. Sensitive data such as tokens does not belong in the .http files, but in the environment files, which are not checked in.


### Magento 2 REST API: Catalog Endpoints
### File: tests/api/magento-catalog.http

### Get all categories
GET {{baseUrl}}/rest/V1/categories
Authorization: Bearer {{adminToken}}
Content-Type: application/json

###

### Get product by SKU
GET {{baseUrl}}/rest/V1/products/{{testSku}}
Authorization: Bearer {{adminToken}}
Content-Type: application/json

###

### Create new category
POST {{baseUrl}}/rest/V1/categories
Authorization: Bearer {{adminToken}}
Content-Type: application/json

{
  "category": {
    "parent_id": 2,
    "name": "Test Category",
    "is_active": true,
    "include_in_menu": true
  }
}

3. Environments: dev, staging, prod without code changes

The environment system is one of the biggest advantages of the PHPStorm HTTP Client over manual curl commands. An http-client.env.json file defines environments together with their variables. An http-client.private.env.json file (not checked in) holds sensitive values such as tokens and passwords. When you run a request, PHPStorm shows a dropdown list of the available environments: one click switches between local, staging and production, without changing a single line in the .http file.

The http-client.env.json file contains non-sensitive configuration values that can be checked into Git: base URL, API version, test SKUs. The http-client.private.env.json file contains sensitive values and is listed in .gitignore. Both files are detected and merged automatically by PHPStorm. Variables from the private file override variables of the same name from the regular env file.


// http-client.env.json (commitable, no secrets)
{
  "local": {
    "baseUrl": "https://mironsoft.local",
    "apiVersion": "V1",
    "testSku": "TEST-SKU-001",
    "storeCode": "default"
  },
  "staging": {
    "baseUrl": "https://staging.mironsoft.de",
    "apiVersion": "V1",
    "testSku": "STAGING-SKU-001",
    "storeCode": "de"
  },
  "production": {
    "baseUrl": "https://mironsoft.de",
    "apiVersion": "V1",
    "testSku": "PROD-SKU-001",
    "storeCode": "de"
  }
}

// http-client.private.env.json (in .gitignore, contains secrets)
{
  "local": {
    "adminToken": "abc123...",
    "customerToken": "def456..."
  },
  "staging": {
    "adminToken": "staging-token...",
    "customerToken": "staging-customer-token..."
  }
}

4. Variables: passing tokens, IDs and response values

Variables in .http files are referenced with double curly braces: {{variableName}}. Besides static variables from the environment files, PHPStorm supports dynamic variables: {{$uuid}} generates a UUID, {{$timestamp}} the current Unix timestamp, {{$randomInt}} a random number. These dynamic variables are useful for generating unique values on every request run without editing data manually.

The most powerful feature is extracting variables from response data. In a response handler script, a value from the response can be written into a global variable, which then becomes available in subsequent requests. The classic use case for Magento: first create an admin token via a POST request, extract the token from the response and write it into {{adminToken}}, then run every following request with that token, all without ever editing the environment files.

5. Testing the Magento 2 REST API

Magento 2 exposes a complete REST API that is ideal for testing with the PHPStorm HTTP Client. The first step of every test session is generating an admin token. The endpoint for that is POST /rest/V1/integration/admin/token with username and password in the body. The returned token is written into a variable by a response handler and reused in every subsequent request.

Magento's REST API follows consistent patterns: GET for reading, POST for creating, PUT for full replacement, PATCH for partial updates, DELETE for deleting. Authentication always happens through the bearer token in the Authorization header. For multistore setups, the store code is part of the URL: /rest/de/V1/products for the German store. The PHPStorm HTTP Client manages these variations through the environment variable {{storeCode}}.


### Magento 2: Auth + Customer Flow
### tests/api/magento-auth-flow.http

### Step 1: Get Admin Token
# @name getAdminToken
POST {{baseUrl}}/rest/V1/integration/admin/token
Content-Type: application/json

{
  "username": "{{adminUsername}}",
  "password": "{{adminPassword}}"
}

> {%
  // Store token for subsequent requests
  client.global.set("adminToken", response.body.replace(/"/g, ""));
  client.test("Status 200", function() {
    client.assert(response.status === 200, "Expected 200, got " + response.status);
  });
%}

###

### Step 2: Get Customer List (uses token from Step 1)
GET {{baseUrl}}/rest/V1/customers/search?searchCriteria[pageSize]=5
Authorization: Bearer {{adminToken}}
Content-Type: application/json

###

### Step 3: Create Customer
POST {{baseUrl}}/rest/V1/customers
Authorization: Bearer {{adminToken}}
Content-Type: application/json

{
  "customer": {
    "email": "test-{{$randomInt}}@mironsoft.de",
    "firstname": "Test",
    "lastname": "Customer",
    "store_id": 1,
    "website_id": 1
  },
  "password": "Test@12345"
}

6. GraphQL queries and mutations in PHPStorm

PHPStorm supports GraphQL in .http files with a special content type: application/json and a body format containing query and optional variables. Alternatively, with the GraphQL plugin, PHPStorm can support native .graphql files with syntax highlighting and schema validation, which are then run through the HTTP Client. Both approaches work well for Magento 2.

Magento 2 has provided GraphQL since version 2.3. The endpoint is consistently /graphql. For authenticated requests (cart, orders, customer data), the customer token is passed in the Authorization header. The PHPStorm setup for GraphQL tests: a magento-graphql.http file with queries and mutations that uses {{baseUrl}}/graphql as the URL and environment variables for tokens and test IDs. The response handler extracts entityId values from mutations for follow-up queries.

7. Response handlers: automatic assertions and variable extraction

Response handlers are JavaScript scripts that run after every request. They enable automatic assertions (similar to Postman tests) and the extraction of values from the response into global variables. The response handler is defined directly in the .http file after the request, inside a > {% %} block.

Two objects are available inside a response handler: response (with status, headers, body and the parsed body as a JavaScript object) and client (with global.set() for setting global variables and test() for defining test assertions). With client.test() you check conditions that are shown in the HTTP Client test runner, similar to unit tests but for API responses.


### GraphQL: Magento 2 Product Query with Response Handler
### tests/api/magento-graphql.http

### Get Product by URL Key
POST {{baseUrl}}/graphql
Content-Type: application/json

{
  "query": "query GetProduct($urlKey: String!) { products(filter: { url_key: { eq: $urlKey } }) { items { id name sku price_range { minimum_price { regular_price { value currency } } } } } }",
  "variables": {
    "urlKey": "{{testProductUrlKey}}"
  }
}

> {%
  client.test("Status 200", function() {
    client.assert(response.status === 200, "Got: " + response.status);
  });
  client.test("Has products", function() {
    const data = response.body;
    client.assert(data.data.products.items.length > 0, "No products returned");
  });
  // Store product ID for next request
  if (response.body.data.products.items.length > 0) {
    client.global.set("productId", response.body.data.products.items[0].id);
  }
%}

###

### Add to Cart Mutation (uses productId from above)
POST {{baseUrl}}/graphql
Authorization: Bearer {{customerToken}}
Content-Type: application/json

{
  "query": "mutation AddToCart($cartId: String!, $sku: String!, $qty: Float!) { addSimpleProductsToCart(input: { cart_id: $cartId, cart_items: [{ data: { quantity: $qty, sku: $sku } }] }) { cart { items { quantity product { name } } } } }",
  "variables": {
    "cartId": "{{cartId}}",
    "sku": "{{testSku}}",
    "qty": 1.0
  }
}

8. HTTP Client vs. Postman: a direct comparison

Feature PHPStorm HTTP Client Postman Advantage
Versioning Git versioning via .http files Export/import, no native Git PHPStorm: API tests in the repo
IDE integration Directly inside PHPStorm External tool, app switching required PHPStorm: no context switch
Environments JSON files, commitable Environments in the app, cloud sync PHPStorm: no vendor lock-in
GraphQL support Native + GraphQL plugin Native with schema support Both good, PHPStorm with plugin
Response handlers JavaScript inside the .http file JavaScript in Postman tests Both equally capable

9. Summary

For PHP developers who already work in PHPStorm, the PHPStorm HTTP Client is a compelling alternative to Postman. Its strength lies not in feature parity, but in integration: .http files live in the Git repository, environments are configured in JSON files, and response handlers enable automatic assertions and variable extraction. For Magento REST and GraphQL APIs this means running authenticated multi-step flows directly from PHPStorm without switching tools.

REST and GraphQL in PHPStorm: the key takeaways

.http files

Check requests into Git as plain text. Organize by topic: one file per API area. ### as the separator between requests.

Environments

http-client.env.json for non-sensitive values (commitable). http-client.private.env.json for tokens (in .gitignore).

Variable extraction

client.global.set() inside the response handler. Token from the login response for all follow-up requests. No manual copy-pasting.

GraphQL

POST /graphql with a JSON body (query + variables). GraphQL plugin for schema validation and autocomplete. Response handlers for assertions.

10. FAQ: testing REST and GraphQL in PHPStorm

1What is the PHPStorm HTTP Client?
An integrated API testing tool. Requests in .http files, commitable into Git. Environments, variables and response handlers without switching tools.
2How to separate requests in .http files?
With ### as the separator. # @name makes requests nameable for references. PHPStorm shows a Run button above every request.
3Keeping tokens out of Git?
http-client.private.env.json in .gitignore. Sensitive values go there. Public values go in http-client.env.json (commitable).
4Testing the Magento 2 REST API?
Token via POST /rest/V1/integration/admin/token. Response handler: client.global.set('adminToken', ...). All follow-up requests with Authorization: Bearer {{adminToken}}.
5Native GraphQL support in PHPStorm?
POST /graphql with a JSON body (query + variables). GraphQL plugin for schema validation and autocomplete. Response handlers for assertions.
6What does the response handler do?
JavaScript block > {% %}. client.test() for assertions, client.global.set() for variable extraction. Similar to Postman tests, directly inside the .http file.
7Switching between environments?
Dropdown on Run click. One click switches local/staging/production for all requests in the session.
8Using .http files in CI/CD?
JetBrains ijhttp CLI runs .http files from the command line. Same files as used locally in PHPStorm, API tests can be integrated into a CI pipeline.
9What are dynamic variables?
{{$uuid}}, {{$timestamp}}, {{$randomInt}}, {{$isoTimestamp}}: recalculated on every run. For unique test data without manual editing.
10Fully replacing Postman?
For PHP teams in PHPStorm, yes. Postman still makes sense for mixed IDE teams, mock servers and extensive API documentation.