All projects

resty

A powerful, modern REST API testing tool that lets you write tests in human-readable format using `.resty` (or `.rest`) files with advanced features like variable substitution, response capture, and multiple output formats. The cool part? A .resty file is just a Markdown file with YAML code blocks defining HTTP requests and tests.

A powerful, modern REST API testing tool that lets you write tests in human-readable format using .resty (or .rest) files with advanced features like variable substitution, response capture, and multiple output formats.

A .resty file is just a Markdown file with YAML code blocks defining HTTP requests and tests.

VSCode Extension

We also have a VSCode extension for Resty. Use the Resty.VSCode extension for the best experience!

Features

Quick Start

Installation

Use the provided build scripts for easy compilation:

# Windows (PowerShell)
./publish.ps1                    # Auto-detects platform, copies to ~/Bin

# Linux/macOS (Bash)
./publish.sh                     # Auto-detects platform, copies to ~/bin

# Windows (Batch)
publish.bat                      # Simple Windows build

Option 2: Manual Build

# Clone and build from source
git clone <repository>
cd Resty
dotnet build

# Run from source
dotnet run --project Resty.Cli -- --help

# Or build single-file executable
dotnet publish Resty.Cli/Resty.Cli.csproj -c Release -r win-x64 --self-contained true /p:PublishSingleFile=true /p:PublishTrimmed=true -o ./publish

💡 Tip: The build scripts automatically detect your platform and create optimized, self-contained executables. See BUILD.md for advanced build options.

Basic Usage

Remember that a .resty file is just a Markdown file with YAML code blocks. If there is a YAML code block with a test: key, it will be treated as a "test block". If the YAML block does not contain a test: key, it will be ignored.

Any "test block" will require at least the test: key and "method" key that contains the URL - the "method" must be get, post, put, patch, delete, head, or options. Other keys are optional.

  1. Create a test file (my-api.resty):
# My API Tests

You can document your tests using standard Markdown syntax.

```yaml
test: get-users
get: https://jsonplaceholder.typicode.com/users
``    <-- only using two backticks here to avoid ending the example markdown block

```yaml
test: create-post
post: https://jsonplaceholder.typicode.com/posts
body: |
  {
    "title": "Test Post",
    "body": "This is a test",
    "userId": 1
  }
capture:
  post_id: id
``    <-- only using two backticks here to avoid ending the example markdown block
  1. Run the tests:
resty my-api.resty

File Format

Resty supports two file extensions:

Both use the same format: Markdown with embedded YAML code blocks.

Test Syntax

Basic Test Structure

test: test-name              # Required: unique test name
get: https://api.example.com # HTTP method and URL
# Supported methods: get, post, put, patch, delete, head, options

Headers and Authentication

test: authenticated-request
post: https://api.example.com/data
headers:
  authorization: Bearer $token
  content-type: application/json
  X-Custom-Header: custom-value
  User-Agent: MyApp/1.0

Request Body

You can write the body as a raw string or as a structured YAML object.

test: post-data
post: https://api.example.com/users
body: |
  {
    "name": "John Doe",
    "email": "john@example.com"
  }

Capture and Expectations

test: login
post: https://api.example.com/auth
body: |
  {
    "username": "admin",
    "password": "secret"
  }
expect:
  status: 200
  headers:
    Content-Type: application/json; charset=utf-8
    X-Request-Id: $request_id
  values:
    - key: $.auth.user.id
      op: greater_than
      value: 0
    - key: $.auth.user.email
      op: endswith
      value: "@example.com"

capture:
  # Extract values from JSON response using JSONPath syntax
  token: $.auth.token
  user_id: $.user.id
  expires: $.auth.expires_at
# Example: Expect a 404 but still capture error information
# The test passes when status is 404 and capture is best-effort.
test: get-missing-resource
get: https://api.example.com/missing
expect:
  status: 404
capture:
  error_message: $.error.message

Variables

# File-level variables
variables:
  base_url: https://api.example.com
  api_version: v1

test: use-variables
get: $base_url/$api_version/users
headers:
  authorization: Bearer $token

Environment Variables

test: env-vars
get: $env:API_BASE_URL/users
headers:
  authorization: Bearer $env:API_TOKEN

Include Files

You can declare shared dependencies for the file in the same top configuration block using dependencies:. These dependencies are tests that must run before any tests in the current file. They are most useful when combined with including .resty files.

Example:

include:
  - variables.yaml
  - variables.private.yaml
  - auth.resty
dependencies:
  - get_token        # test defined in auth.resty

Notes:

# Load shared variables from external files
# - .yaml/.yml files load variables only (with nested includes and precedence)
# - .rest/.resty files make their tests available for dependency resolution
#   (so you can `requires:` tests defined in them). Only tests you select in
#   this file will run; dependencies from included files will run if required.
include:
  - variables.yaml
  - secrets.yaml
  - auth.resty   # provides tests like 'get_token' for requires

Command Line Usage

Note about Flags

The command line flag-operator is completely interchangeable: -, --, or /. For example, there is no difference between -o, --o, and /o. Same goes for -help, --help, and /help.

Therefore, there is no chaining of single-dash flags like -rv to mean -r -v.

I won't change that behavior, because I'm tired of not knowing what to use for flags in different environments, because every tool does it differently.

Technically, all - and / characters are removed at the beginning of each flag.

while (arg.StartsWith('-') || arg.StartsWith('/')) {
  isFlag = true;
  arg = arg.Substring(1);
}

So you can even do ---verbose or ////help if you want.

Basic Commands

resty [--all|-a]                # Run all tests in current directory recursively
resty --help|-h|-?              # Show help
resty --version|-v              # Show detailed version (-v shows only version number)
resty --verbose|-e              # Enable verbose output

Test Selection

resty auth/                     # Run all tests in auth/ directory (recursive)
resty auth/ -r false            # Run tests only in auth/ directory (non-recursive)
resty auth/login.resty          # Run specific file
resty -t login                  # Run test named 'login'
resty -t login,logout           # Run multiple specific tests
resty -f auth                   # Run tests containing 'auth' in name
resty -f api,user               # Run tests matching any pattern
resty --list                    # List all available tests
resty --dry-run                 # Validate tests without running

Output Formats

resty -o text                   # Default console output
resty -o json                   # JSON output
resty -o xml                    # JUnit XML for CI
resty -o html                   # Interactive HTML report
resty -s results.json           # Save to file
resty -o html -s report.html    # HTML report saved to file

Advanced Options

resty --timeout 60              # Set request timeout in seconds
resty --recursive false         # Search only top-level directory
resty --parallel 4              # Parallel execution (future)
resty --color false             # Disable colored console output
resty -v -o json -s full.json   # Verbose JSON output to file
resty -o html -s report.html    # Interactive HTML report

Output Examples

Console Output

═══════════════════════════════════════════════════════════════════
                          TEST RESULTS
═══════════════════════════════════════════════════════════════════

Total Tests:    3
Passed:         2 (66.7%)
Failed:         1
Skipped:        0
Duration:       1.23s

📁 api-tests.resty
   /path/to/api-tests.resty

  ✅ get-users (0.456s)
  ✅ create-post (0.234s)
  ❌ delete-post (0.123s)
     Error: HTTP 404 Not Found

═══════════════════════════════════════════════════════════════════
❌ TESTS FAILED (2/3 passed in 1.23s)
═══════════════════════════════════════════════════════════════════

JSON Output

{
  "summary": {
    "totalTests": 3,
    "passedTests": 2,
    "failedTests": 1,
    "skippedTests": 0,
    "passRate": 66.67,
    "duration": 1.234,
    "startTime": "2025-01-16T10:30:00Z",
    "endTime": "2025-01-16T10:30:01Z"
  },
  "results": [...],
  "metadata": {
    "tool": "Resty",
    "version": "1.0.0",
    "environment": {
      "os": "Windows 11",
      "runtime": ".NET 9.0"
    }
  }
}

Advanced Features

JSONPath Reference

Resty uses JSONPath syntax for extracting values from JSON responses. Here's a comprehensive guide:

Basic Syntax

JSONPath Description Example Response Extracted Value
$.field Root level field {"name": "John"} "John"
$.nested.field Nested object {"user": {"name": "John"}} "John"
$.array[0] First array element {"items": [1, 2, 3]} 1
$.array[-1] Last array element {"items": [1, 2, 3]} 3
$.array[*] All array elements {"items": [1, 2, 3]} [1, 2, 3]

Real-World Examples

# API Response:
# {
#   "result": {
#     "token": "eyJhbGciOiJIUzI1NiIs...",
#     "user": {
#       "id": 123,
#       "email": "user@example.com"
#     }
#   },
#   "status": "success"
# }

test: login
post: /api/auth
capture:
  # Extract the token
  auth_token: $.result.token

  # Extract user information
  user_id: $.result.user.id
  user_email: $.result.user.email

  # Extract status
  api_status: $.status
# API Response with Arrays:
# {
#   "data": {
#     "users": [
#       {"id": 1, "name": "Alice"},
#       {"id": 2, "name": "Bob"}
#     ]
#   }
# }

test: get-users
get: /api/users
capture:
  # Get first user's ID
  first_user_id: $.data.users[0].id

  # Get all user names
  all_names: $.data.users[*].name

  # Get last user's name
  last_user_name: $.data.users[-1].name

Common Patterns

Notes

Variable Precedence

  1. Captured variables (from previous test responses) - Highest
  2. File-level variables (in YAML blocks)
  3. Included variables (from external files)
  4. Environment variables ($env:NAME) - Lowest

Response Extraction

Capture strictness:

Header expectations:

Use JSONPath syntax to extract values from JSON responses:

capture:
  # Basic field extraction
  simple_field: $.name

  # Nested object properties
  nested_field: $.user.profile.email

  # Array elements
  first_item: $.items[0].id
  last_item: $.items[-1].id

  # Array properties
  all_names: $.items[*].name

  # Complex paths
  token: $.result.auth.token
  user_id: $.data.user.id

Test Dependencies

Resty supports explicit test dependencies using the requires property. When a test has dependencies, those dependencies are automatically run first:

# Test 1: Login (no dependencies)
test: login
post: /auth/login
capture:
  token: $.access_token
# Test 2: Requires login test to run first
test: protected-endpoint
requires: login
get: /api/protected
headers:
  authorization: Bearer $token

Single Dependency

test: get-profile
requires: login
get: /api/profile
headers:
  authorization: Bearer $token

Multiple Dependencies

test: update-profile
requires:
  - login
  - get-profile
put: /api/profile
headers:
  authorization: Bearer $token
body: |
  {
    "name": "Updated Name"
  }

Dependency Chain

Dependencies can form chains - Resty automatically resolves the correct execution order:

test: login
post: /auth/login
capture:
  token: $.access_token
test: get-profile
requires: login
get: /api/profile
headers:
  authorization: Bearer $token
capture:
  user_id: $.id
test: update-profile
requires: get-profile  # This will run login → get-profile → update-profile
put: /api/profile
headers:
  authorization: Bearer $token

Running Specific Tests

When you run a specific test, its dependencies are automatically included:

# This will run 'login' first, then 'update-profile'
resty test.rest -t update-profile

# Includes: You can include auth.resty in your test file and require its tests
# In your-file.resty:
# ```yaml
# include:
#   - variables.yaml
#   - auth.resty
# ```
# ```yaml
# test: protected-endpoint
# requires: get_token   # defined in auth.resty
# get: $base_url/api/protected
# headers:
#   authorization: Bearer $token
# ```

Error Handling

By default, Resty searches directories recursively for test files:

# These are equivalent (recursive is default)
resty auth/
resty auth/ --recursive true
resty auth/ -r true

# Search only the specified directory (no subdirectories)
resty auth/ --recursive false
resty auth/ -r false

Use --recursive false when:

VSCode Integration

For the best development experience, add to your VSCode settings:

{
  "files.associations": {
    "*.resty": "markdown",
    "*.rest": "markdown"
  }
}

This provides:

Architecture

Resty/
├── Resty.Core/              # Core parsing and execution logic
│   ├── Helpers/             # Helper classes and utilities
│   ├── Models/              # Domain models
│   ├── Parsers/             # File and YAML parsing
│   ├── Variables/           # Variable resolution engine
│   ├── Execution/           # HTTP execution and test running
│   └── Output/              # Result formatters (Console, JSON, XML)
├── Resty.Cli/               # Command-line interface
└── Resty.Tests/             # Unit and integration tests

Exit Codes

Development

# Clone and build
git clone <repository>
cd Resty
dotnet restore
dotnet build

# Run tests
dotnet test

# Run CLI
dotnet run --project Resty.Cli -- --help

# Create package
dotnet pack