API Reference
Complete reference documentation for HTTP File Runner syntax, options, and features.
Command Line Interface
Synopsis
httprunner [OPTIONS] [FILE...]
httprunner [OPTIONS] --discover
Arguments
Options
Examples
# Basic usage
httprunner api-tests.http
# Multiple files
httprunner auth.http users.http posts.http
# Verbose mode with pretty-printed JSON
httprunner api-tests.http --verbose --pretty-json
# Add delay between requests
httprunner api-tests.http --delay 500
# Accept self-signed certificates
httprunner api-tests.http --insecure
# Discovery mode with logging
httprunner --discover --verbose --log test-results.log
# Generate summary report (defaults to markdown)
httprunner api-tests.http --report
# Generate HTML summary report
httprunner api-tests.http --report html
# Run without donation banner
httprunner api-tests.http --no-banner
# Export individual requests and responses
httprunner api-tests.http --export
# Generate markdown summary report (explicit)
httprunner api-tests.http --report markdown
# Export requests and responses to individual timestamped files
httprunner api-tests.http --export
# Export with pretty-printed JSON
httprunner api-tests.http --export --pretty-json
# Environment-specific testing with formatted JSON output and HTML report
httprunner api-tests.http --env production --verbose --pretty-json --log prod-test.log --report html
# Combine export with report generation
httprunner api-tests.http --export --report html --pretty-json
HTTP File Syntax
File Structure
[comments]
[variables]
[request-block]
[assertions]
[request-block]
[assertions]
...
Request Block Format
METHOD URL [HTTP-VERSION]
[Header-Name: Header-Value]
...
[request-body]
Supported HTTP Methods
Comments
# This is a comment
# Comments start with # and continue to end of line
GET https://api.example.com/users # Inline comments are also supported
Headers
GET https://api.example.com/users
Authorization: Bearer token123
Accept: application/json
Content-Type: application/json
X-Custom-Header: custom-value
Request Body
# JSON body
POST https://api.example.com/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}
# Form data
POST https://api.example.com/upload
Content-Type: application/x-www-form-urlencoded
name=John&email=john@example.com
# Text body
POST https://api.example.com/notes
Content-Type: text/plain
This is a plain text note.
Variables
Variable Definition
@variable-name=value
Variable Usage
{{variable-name}}
Variable Scoping Rules
- Variables must be defined before they can be used
- Variables are file-scoped (each .http file has its own variable namespace)
- Later variable definitions override earlier ones with the same name
- Variables can reference other variables that were defined earlier
Variable Composition
@protocol=https
@hostname=api.example.com
@port=443
@version=v1
@baseUrl={{protocol}}://{{hostname}}:{{port}}/{{version}}
GET {{baseUrl}}/users
Valid Variable Names
- Must start with a letter or underscore
- Can contain letters, numbers, underscores, and hyphens
- Case-sensitive
- No spaces allowed
Variable Usage Locations
- URLs
- Header names and values
- Request body content
- Other variable definitions
Built-in Functions
Function List
| Function | Description | Example Output |
|---|---|---|
guid() |
Generate UUID v4 (32 hex chars) | a1b2c3d4e5f67890a1b2c3d4e5f67890 |
string() |
Random alphanumeric string (20 chars) | aB3xK9mP2q |
number() |
Random number (0-100) | 42 |
base64_encode('text') |
Base64 encode a string | dGV4dA== |
upper('text') |
Convert string to uppercase | TEXT |
lower('TEXT') |
Convert string to lowercase | text |
name() |
Generate random full name | John Smith |
first_name() |
Generate random first name | Sarah |
last_name() |
Generate random last name | Johnson |
address() |
Generate random full mailing address (street, city, postal code, country) | 123 Main Street, Springfield, 12345, USA |
email() |
Generate random email address | john.smith@example.com |
job_title() |
Generate random job title | Senior Software Engineer |
lorem_ipsum(N) |
Generate Lorem Ipsum placeholder text with N words | lorem ipsum dolor sit amet... |
getdate() |
Get current local date (YYYY-MM-DD) | 2026-01-26 |
gettime() |
Get current local time (HH:MM:SS) | 15:38:26 |
getdatetime() |
Get current local date and time (YYYY-MM-DD HH:MM:SS) | 2026-01-26 15:38:26 |
getutcdatetime() |
Get current UTC date and time (YYYY-MM-DD HH:MM:SS) | 2026-01-26 15:38:26 |
Usage Notes
- All functions are case-insensitive
- Can be used in URLs, headers, and request bodies
- Values are generated dynamically for each request
- Can be combined with variables
base64_encode(),upper(), andlower()require single-quoted string argumentslorem_ipsum(N)requires a numeric parameter specifying the number of words to generate
Example
POST https://api.example.com/test
Content-Type: application/json
{
"id": "guid()",
"key": "string()",
"value": "number()",
"auth": "base64_encode('user:pass')",
"name": "name()",
"email": "email()",
"address": "address()",
"description": "lorem_ipsum(50)",
"eventDate": "getdate()",
"timestamp": "getdatetime()",
"utcTime": "getutcdatetime()"
}
Request Variables
Syntax Pattern
{{<request_name>.(request|response).(body|headers).(*|JSONPath|XPath|<header_name>)}}
Component Breakdown
| Component | Description | Example |
|---|---|---|
request_name |
Name of a previous request (defined with # @name) |
authenticate |
request|response |
Extract from request or response | response |
body|headers |
Extract from body or headers | body |
extraction_path |
JSONPath, XPath, header name, or * |
$.json.access_token |
JSONPath Patterns
$.property- Top-level property$.nested.property- Nested property$.json.property- Property within "json" field*- Entire body content
Header Extraction
Content-Type- Extract Content-Type headerauthorization- Extract Authorization header (case-insensitive)x-custom-header- Extract custom header
Request Naming
# @name request_identifier
POST https://api.example.com/auth
Content-Type: application/json
{
"username": "user",
"password": "pass"
}
Usage Examples
# Extract from response body
{{auth.response.body.$.access_token}}
# Extract from response headers
{{auth.response.headers.Content-Type}}
# Extract from request body
{{auth.request.body.$.username}}
# Extract entire response
{{auth.response.body.*}}
Execution Order
- Request variables can only reference requests that appear earlier in the file
- Referenced requests must have been executed successfully
- Named requests must use the
# @namesyntax - Variables are resolved at execution time
Request Directives
Request directives are special comment annotations that control request behavior and execution.
Directive Syntax
# @directive-name [value]
// @directive-name [value]
Available Directives
| Directive | Description | Example |
|---|---|---|
@name |
Assign a name to a request for referencing in request variables | # @name authenticate |
@timeout |
Set read timeout (max time to wait for response data). Units: s (seconds, default), m (minutes), ms (milliseconds) | # @timeout 120# @timeout 2 m# @timeout 5000 ms |
@connection-timeout |
Set connection timeout (max time to establish connection). Units: s (seconds, default), m (minutes), ms (milliseconds) | // @connection-timeout 10// @connection-timeout 500 ms |
@pre-delay |
Wait specified milliseconds before executing the request | # @pre-delay 1000 |
@post-delay |
Wait specified milliseconds after executing the request | # @post-delay 500 |
@dependsOn |
Execute only if specified request succeeded | # @dependsOn authenticate |
@if |
Conditional execution based on status code or response body/header content | # @if authenticate.response.status 200# @if user.response.body.$.role admin |
@if-not |
Conditional execution - execute only if condition does NOT match | # @if-not user.response.status 404# @if-not user.response.body.$.role guest |
Directive Examples
# Named request with timeout
# @name login
# @timeout 30
POST https://api.example.com/auth/login
Content-Type: application/json
{"username": "user", "password": "pass"}
###
# Request with pre-delay and connection timeout
# @pre-delay 2000
// @connection-timeout 5
GET https://api.example.com/status
###
# Conditional execution with dependencies
# @name getUser
# @dependsOn login
# @if login.response.status 200
GET https://api.example.com/user/profile
Authorization: Bearer {{login.response.body.$.token}}
###
# Negative condition - only if user doesn't exist
# @if-not getUser.response.status 200
POST https://api.example.com/user/create
Content-Type: application/json
{"username": "newuser"}
Notes
- Directives must appear before the HTTP request they apply to
- Both
#and//comment styles are supported - Multiple directives can be applied to a single request
- Timeout values default to seconds if no unit is specified
- Delay values are always in milliseconds
Environment Files
File Name
http-client.env.json
File Location
The environment file should be placed in:
- Same directory as the .http file
- Any parent directory of the .http file
JSON Schema
{
"environment-name": {
"variable-name": "value",
"another-variable": "another-value"
},
"another-environment": {
"variable-name": "different-value"
}
}
Complete Example
{
"dev": {
"BaseUrl": "https://localhost:44320",
"ApiKey": "dev-key-123",
"Database": "dev_db",
"LogLevel": "debug"
},
"staging": {
"BaseUrl": "https://staging-api.example.com",
"ApiKey": "staging-key-456",
"Database": "staging_db",
"LogLevel": "info"
},
"production": {
"BaseUrl": "https://api.example.com",
"ApiKey": "prod-key-789",
"Database": "prod_db",
"LogLevel": "warn"
}
}
Variable Override Order
- Environment variables from http-client.env.json (loaded first)
- Variables defined in .http file (override environment variables)
Response Assertions
Assertion Types
Assertion Syntax
METHOD URL
[headers]
[body]
EXPECTED_RESPONSE_STATUS status-code
EXPECTED_RESPONSE_BODY "expected-text"
EXPECTED_RESPONSE_HEADERS "Header-Name: expected-value"
Multiple Assertions
GET https://api.example.com/users/1
EXPECTED_RESPONSE_STATUS 200
EXPECTED_RESPONSE_BODY "John Doe"
EXPECTED_RESPONSE_BODY "john@example.com"
EXPECTED_RESPONSE_HEADERS "Content-Type: application/json"
EXPECTED_RESPONSE_HEADERS "Cache-Control: no-cache"
Assertion Matching Rules
Assertion Behavior
- All assertions must pass for the request to be considered successful
- If any assertion fails, the request is marked as failed
- Assertions are evaluated in the order they appear
- When assertions are present, response headers and body are always captured
Output Formats
Default Output
🚀 HTTP File Runner - Processing file: requests.http
==================================================
Found 3 HTTP request(s)
✅ GET https://api.example.com/users - Status: 200
❌ GET https://api.example.com/missing - Status: 404
✅ POST https://api.example.com/users - Status: 201
==================================================
File Summary: 2 Passed, 1 Failed, 0 Skipped
Verbose Output
🚀 HTTP File Runner - Processing file: requests.http
==================================================
Found 1 HTTP request(s)
📤 Request Details:
Method: GET
URL: https://api.example.com/users
Headers:
Authorization: Bearer token123
Accept: application/json
------------------------------
✅ GET https://api.example.com/users - Status: 200 - 145ms
📥 Response Details:
Status: 200
Duration: 145ms
Headers:
content-type: application/json
content-length: 1234
server: nginx/1.18.0
Body:
[{"id":1,"name":"John Doe","email":"john@example.com"}]
------------------------------
Report Formats (--report)
The --report flag generates timestamped reports in either markdown or HTML format. Defaults to markdown if no format is specified.
Markdown Report Example
# HTTP File Runner - Test Report
**Generated:** 2025-12-19 09:34:12
## Overall Summary
- **Total Requests:** 15
- **Passed:** ✅ 12
- **Failed:** ❌ 2
- **Skipped:** ⏭️ 1
- **Success Rate:** 80.0%
---
## File: `api-tests.http`
| Method | URL | Status | Duration | Result |
|--------|-----|--------|----------|--------|
| GET | https://api.example.com/users | 200 | 145ms | ✅ |
| POST | https://api.example.com/users | 201 | 203ms | ✅ |
| GET | https://api.example.com/missing | 404 | 98ms | ❌ |
**File Summary:** 2 Passed, 1 Failed, 0 Skipped
HTML Report Features
HTML reports (--report html) include all the same information with additional features:
- Responsive Design: Works on mobile and desktop devices
- Light/Dark Mode: Automatic theme switching based on system preferences
- Color-Coded Statistics: Visual cards showing pass/fail/skip counts
- Modern Styling: Clean, professional UI with proper spacing
- Syntax Highlighting: Formatted code blocks for request/response bodies
Report files are named:
- Markdown:
httprunner-report-YYYYMMDD-HHMMSS.md - HTML:
httprunner-report-YYYYMMDD-HHMMSS.html
Export Mode (--export)
The --export flag saves individual HTTP requests and responses to separate timestamped log files. Each request generates two files: one for the request and one for the response.
Use Cases
- API Documentation: Create file-based documentation of API interactions with real requests and responses
- Debugging & Troubleshooting: Preserve exact HTTP request/response pairs for detailed analysis
- Test Artifacts: Generate reusable request/response examples for testing and development
- Compliance & Auditing: Keep detailed records of API communications with timestamps
- Request Replay: Save requests in a format that can be easily replayed or modified
File Format
Export files are named using the pattern: {request_name}_{type}_{timestamp}.log
{request_name}: From# @namedirective or auto-generated{type}: Either "request" or "response"{timestamp}: Unix timestamp to ensure uniqueness
Example Output
✅ Exported requests and responses to files
✅ Exported GET_users_request_1738016400.log
✅ Exported GET_users_response_1738016400.log
✅ Exported POST_login_request_1738016400.log
✅ Exported POST_login_response_1738016400.log
Request File Format
GET https://api.example.com/users
Authorization: Bearer token123
Accept: application/json
Response File Format
HTTP/1.1 200
Content-Type: application/json
Content-Length: 156
{
"users": [
{"id": 1, "name": "John Doe"}
]
}
Combining with Other Flags
--export --pretty-json: Format JSON content in exported files--export --verbose: Show verbose terminal output while exporting--export --report html: Generate both exports and summary report--discover --export: Export all discovered .http file requests
Discovery Mode Output
🔍 Discovering .http files recursively...
Found 4 .http file(s):
📄 .\tests\auth.http
📄 .\tests\users.http
📄 .\examples\simple.http
📄 .\api\health.http
🚀 HTTP File Runner - Processing file: .\tests\auth.http
==================================================
Found 2 HTTP request(s)
...
🎯 Overall Summary:
Files processed: 4
Total requests: 12 Passed, 2 Failed, 1 Skipped
Assertion Output
✅ GET https://api.example.com/users - Status: 200 - 123ms
🔍 Assertion Results:
✅ Status code: Expected 200, Got 200
✅ Response body contains: "John Doe"
❌ Response header: Expected "Cache-Control: no-cache", Got "Cache-Control: max-age=3600"
❌ Request failed due to assertion failures
Status Indicators
Exit Codes
Success Criteria
A request is considered successful when:
- HTTP status code is in 2xx range (200-299)
- All assertions (if any) pass
- No network or connection errors occur
Failure Scenarios
- HTTP status code is not 2xx (4xx, 5xx)
- Any assertion fails
- Network connection error
- DNS resolution failure
- Timeout
- Invalid URL format
Version Information
Version Command
httprunner --version
httprunner -v
Version Output Format
HTTP File Runner v1.2.3
Git Tag: v1.2.3
Git Commit: a1b2c3d4e5f6789
Build Time: 2025-06-19 10:30:45 UTC
Version Components
Build Information
Version information is automatically generated at build time using:
- Git repository metadata
- Build system timestamp
- Semantic versioning from git tags