100% Free & Open Source

API testing without limits.

Build, test, and share your APIs with a self-hosted tool that does what you actually need. Scripts, environments, OAuth 2.0, code generation, AI-powered collections, visual test flows, WebSocket & GraphQL, shared API docs, local proxy mode, and backend code generation — no account required, no limits.

Standalone Desktop All-in-one app. No server required. Data stored locally.
Desktop Client Connects to your own server. Ideal for teams and shared workspaces.
Self-Hosted Web Run the backend + web UI on your server with Docker or manual setup.
OpenReq — My Workspace
Collections
GET /users
POST /auth/login
GET /products
PUT /users/{id}
DEL /sessions
GET /orders
POST /checkout
POST
{{base_url}}/auth/login
Send
Params
Headers
Body
Auth
Scripts
{
  "email": "dev@openreq.io",
  "password": "{{env_password}}"
}
200 OK 142 ms 1.2 KB

Everything you'd expect. And then some.

18 core features — from request building and scripting to AI-powered generation, shared docs, local proxy, and backend code export. Everything you need for your entire API lifecycle.

Request Builder

All HTTP methods, query params, headers, body (JSON/XML/form-data/urlencoded), path parameters with {{variable}} syntax. First-class WebSocket and GraphQL protocol support. Tab-based — work on multiple requests at once.

5 Auth Methods

Bearer token, Basic Auth, API Key, and full OAuth 2.0 with Authorization Code, Client Credentials, and PKCE. Token exchange built right in.

Pre/Post Scripts

Python & JavaScript scripting engine with full syntax support. req API — req.test(), req.expect(), req.variables, req.request, req.sendRequest(). Collection-level scripts, variable persistence, and AI-assisted script generation.

Scripting Guide →

Environments

Manage variables per environment (DEV, TEST, LIVE). Secret values, environment switching from the top bar, variable insertion in any field. Workspace isolation included.

Code Generation

Turn any request into working code: cURL, Python, JavaScript (fetch & axios), Go, Java, C#, PHP. Copy-paste into your project and go.

AI Collection Builder

Paste API docs or provide a URL. The AI wizard parses endpoints and generates a full collection with methods, URLs, headers, and bodies. Review before import.

Response Visualizer

Pretty, Raw, Tree, and Preview modes. JSON tree with collapse/expand, HTML/SVG rendering, status codes, response time, size — everything you need at a glance.

WebSocket Proxy

WebSocket and GraphQL as first-class request types alongside HTTP. Connect to WebSocket servers, send/receive messages, or build GraphQL queries with dedicated editors. All through the built-in proxy.

Import / Export

Import from Postman format (v2.1), OpenAPI 3.0+ specs, or raw cURL commands. Export back to Postman format. Migrate your existing workflow in seconds.

Visual Test Builder

Build complex API test flows visually with a drag-and-drop node graph canvas. Connect HTTP requests, assertions, delays, conditions, loops and scripts. Real-time SSE execution with animated edges and run reports.

AI Agent "George"

An intelligent AI assistant that understands your entire scripting API. Ask George to write pre/post scripts, debug assertions, explain responses, or generate test flows. Streaming chat with conversation history and full context awareness.

Ollama Integration

Run AI features locally with Ollama — no cloud API key required. Auto-detected models, seamless switching between OpenAI and Ollama. Full privacy, zero data leaving your machine.

Share API Docs

Generate beautiful, read-only API documentation from any collection and share it via a public link. Optional password protection. Redoc-style layout with sidebar navigation — perfect for external teams or clients.

Local Proxy Mode

Self-host the server anywhere and reach local networks remotely. The Chrome Extension or Electron client executes HTTP requests from your machine while the server handles scripts, auth, and variables. Perfect for testing internal APIs.

Collection Runner

Run entire collections in sequence with real-time SSE streaming. See per-request results as they execute, save run reports to the database, and export as JSON or HTML. Postman-style batch execution built in.

DNS & Ping Tools

Built-in network diagnostics right from the URL bar. Resolve DNS records or ping hosts to troubleshoot connectivity before sending requests. No need to leave the app for basic debugging.

Postman pm.* Compat

Full Postman compatibility layer — pm.test(), pm.expect(), pm.globals, pm.environment, pm.collectionVariables all work. Migrate your Postman scripts without rewriting a single line.

Python scripting engine.

Write pre-request scripts to prepare your API calls and post-response tests to validate everything. Full Python syntax with a req API.

  • req.test() assertions with auto-fail on error
  • req.request.headers / url / method / body — direct manipulation
  • req.sendRequest() — call APIs from your scripts
  • req.expect() chainable assertions (to_equal, to_include, to_match...)
  • Collection-level scripts with variable persistence
  • JavaScript mode with auto-transpilation to Python
Read the Scripting Guide
post-response.py
# Validate response & extract data
req.test("Status is 200", req.response.status == 200)
req.test("Fast response", req.response.time < 500)

data = req.response.json
req.test("Has items", len(data) > 0)

# Check each item
for i, item in enumerate(data):
  req.test(f"Item {i} has id", item.id is not None)

# Save for next request
req.variables.set("first_id", data[0].id)
print(f"Found {len(data)} items")
AI-Powered

Paste docs.
Get a full collection.

Don't manually create requests one by one. Drop in your API documentation — or just a URL — and the AI wizard generates an entire collection: endpoints, methods, headers, request bodies. All of it. You pick what to import.

1

Provide documentation

Paste raw API docs, a Swagger page URL, or any documentation source. The wizard fetches and understands the structure.

2

AI parses & generates

Endpoints are extracted with their HTTP methods, paths, headers, query params, and example request bodies. Streamed in real-time.

3

Review & import

Preview every generated endpoint. Select what you need, deselect what you don't, then batch-import into your collection with one click.

AI Collection Wizard
1 Input
2 Generate
3 Preview
4 Import
Generated Endpoints
7 endpoints found
GET /api/users List all users
POST /api/users Create user
GET /api/users/{id} Get user by ID
PUT /api/users/{id} Update user
DEL /api/users/{id} Delete user
POST /api/auth/login Authenticate
POST /api/auth/refresh Refresh token
Visual Testing

Drag. Connect.
Run your test flow.

Build complex API test workflows on a visual canvas. Drag nodes from the palette, connect them with edges, set conditions and assertions — then hit Run and watch your flow execute in real-time with animated edges and per-node results.

HTTP Request
Assertion
Condition
Delay
Script
Loop
Set Variable
Collection
Group
Real-time SSE execution
Branching (True/False)
Run reports & export
Drag from sidebar
User Auth Flow
▶ Run Save
HTTP POST Login POST
200 89 ms
VAR Save Token
auth_token = {{response.token}}
HTTP GET Profile GET
200 42 ms
Validate Profile 2/2
status_code: 200
json $.email exists
4/4 Passed 131 ms
How Local Proxy Works
OpenReq Server
Scripts, Auth, Variables
Your Browser / Desktop
Executes HTTP from your network
Internal API
192.168.x.x / localhost

Chrome Extension

Install the MV3 extension. It bridges requests from the server to your local network via the browser — no extra setup.

Electron Desktop

The Windows desktop client acts as a local proxy natively. Point it to your server and reach any network your machine can access.

Local Proxy

Your server, anywhere.
Their network, reached.

Self-host OpenReq in the cloud and test internal APIs on a remote network. The server handles scripting, auth, and variable resolution — but the actual HTTP request fires from your machine. Perfect when you can't install the server locally but need to hit internal endpoints.

Server resolves {{variables}}, runs pre/post scripts, handles OAuth
Client executes the actual HTTP request from your local machine
HMAC-signed tokens secure the prepare/complete handshake
Switch between Server and Local mode with one click

See it in action

A walkthrough of the core interface — request building, code generation, scripting, and response visualization.

GET /api/v1/users — Response
200 OK
87 ms 2.4 KB application/json
Pretty
Raw
Tree
Preview
Headers
"data": [
{
"id": "a3f8c2e1-...",
"username": "johndoe",
"email": "john@example.com",
"role": "admin",
"active": true,
"created_at": "2026-01-15T09:30:00Z"
},
{ ... 2 more items }
],
"total": 3,
"page": 1
Code Generation — POST /auth/login
cURL
Python
JS fetch
JS axios
Go
Java
C#
PHP
import requests

url = "https://api.example.com/auth/login"
payload = {
  "email": "dev@openreq.io",
  "password": "my_secret"
}
headers = {
  "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.status_code)
print(response.json())
Post-Response Script — Test Assertions
Login
Users
Billing
1 // Validate login response
2 req.test("Status is 200", () => {
3   req.response.status === 200
4 })
5
6 req.test("Has token", () => {
7   req.response.json.token !== null
8 })
9
10 // Save token for next requests
11 req.variables.set(
12   "auth_token",
13   req.response.json.token
14 )
Test Results
PASS Status is 200
PASS Has token
Console
[variable] auth_token = "eyJhbGci..."
All tests passed
2/2 · 142 ms
Import/Export — Collection Management

Import Collections

Import from Postman
Import collections from Postman format with environments
OpenAPI
Parse OpenAPI/Swagger specs (v2/v3)
cURL
Paste any cURL command to create request
Import Preview
Collection file (.json)
Folders
3
Requests
12
📁 Authentication (3 requests)
└─ POST /auth/login
└─ GET /auth/refresh
└─ POST /auth/logout
📁 Users (5 requests)
📁 Products (4 requests)

Export Collections

Postman Format (v2.1)
Export to Postman v2.1 format
Export
JSON Backup
Full backup with scripts and variables
Export
AI Collection Wizard — Generating from docs
Source: URL
https://api.stripe.com/docs/openapi
Generation complete 12.4s · 23 endpoints parsed
Payments
8 endpoints
Customers
6 endpoints
Subscriptions
5 endpoints
Webhooks
4 endpoints
POST /v1/payment_intents
  Content-Type: application/json
  Authorization: Bearer {{api_key}}
  { "amount": 2000, "currency": "usd" }
GET /v1/customers/{id}
  Authorization: Bearer {{api_key}}
  Accept: application/json
  // No request body
Visual Test Builder — Flow Editor
HTTP Login POST
200 142 ms
Assertion 0/1
status_code: 201
False
True False
HTTP Retry SKIPPED
HTTP Fallback GET
200 35 ms
Nodes
● HTTP Request
● Assertion
● Condition
● Delay
● Script
● Loop
▶ Run
Auto-layout
AI Agent "George" — Chat Assistant
Conversations
Script help
Debug 401 error
Generate tests
Explain response
Write a post-response script that saves the auth token from login response to a variable
G
George
Here's a post-response script that extracts the token:
data = req.response.json()
token = data.get("access_token")
req.variables.set("auth_token", token)
req.log("Token saved: " + token[:20])
Ask George anything...
Settings — AI Provider Configuration
AI Provider
OpenAI
Ollama
Base URL
http://localhost:11434
Model
llama3.1:latest
Available Models
llama3.1:latest
4.7 GB
codellama:13b
7.4 GB
mistral:7b
4.1 GB
deepseek-coder:6.7b
3.8 GB
Connected to Ollama — 4 models available

Up and running
in two minutes.

Clone, docker-compose up, done. No cloud accounts, no API keys (unless you want AI features), no subscription tiers to compare.

1

Clone the repo

Grab the source from GitHub.

2

Start with Docker

One command spins up the API and frontend.

3

Open your browser

Navigate to localhost:8000. That's it.

Terminal
# Clone the repository
$ git clone https://github.com/n1kozor/OpenReq.git
$ cd OpenReq

# Start everything with Docker
$ docker compose up -d
✓ Container openreq-api   Started
✓ Container openreq-web   Started

# Open in browser
$ open http://localhost:8000

Ready. No sign-up required.

OpenReq Standalone

Everything bundled in one installer: frontend + backend. Start instantly — no server required.

Note: Data is stored locally on your machine (SQLite). Perfect for offline use or personal workflows.
Download Standalone Windows
All-in-One
Frontend and backend bundled into a single app.
Zero Setup
Install and run immediately. No server configuration.
Local Data
SQLite stored on your machine. Works offline.

Windows Desktop Client

A native desktop experience built with Electron. Install the client on Windows and connect it to your self-hosted OpenReq backend.

Note: This is a front-end client only. The backend API must be hosted separately — either via Docker or manual setup. The desktop app connects to your running backend instance. macOS and Linux versions are in progress.
Download Client for Windows v1.1.21
Native Window Experience
Runs as a standalone Windows application with its own window, tray icon, and system integration.
Easy Setup
One-click installer (.exe). Point it to your backend URL and you're ready to go.
Connects to Your Backend
The desktop app is a client only — your API backend runs via Docker or manual setup on your server.

Built with modern tools

Solid foundations, no bloat. Every dependency earns its place.

FastAPI
Backend
React 19
Frontend
🔧
TypeScript
Type Safety
🗄
SQLite
Database
🎨
MUI 6
Components
🚀
Vite
Build Tool
🔐
JWT
Auth
🐳
Docker
Deployment

Your APIs, your rules.

Stop paying for features that should be free. Self-host OpenReq and own your entire API workflow.

MIT License · Free forever · Community-driven

80+ Endpoints

API Reference

Complete REST API documentation for OpenReq.
Base URL: /api/v1/

19
Resource Groups
JWT
Bearer Auth
REST
+ WebSocket
Overview

Base URL

All endpoints are prefixed with /api/v1/. Responses are JSON with UTF-8 encoding.

Authentication

JWT Bearer token required for most endpoints. Obtain via POST /auth/login.

Response Format

JSON responses. Success: resource or list. Errors: {"detail": "message"} with HTTP status codes.

Error Handling

400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Validation Error.

Authentication

OpenReq uses JWT Bearer tokens for API authentication. To access protected endpoints, include the token in the Authorization header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

To obtain a token:

  • If no users exist, use POST /setup/initialize to create the first admin (no auth required)
  • Otherwise, use POST /auth/login with email and password

Public endpoints (no auth required): /setup/* and /ws-proxy WebSocket.

Example: Login & Use Token
# 1. Login
curl -X POST /api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@example.com","password":"secret"}'

# Response: {"access_token": "eyJhbG...", "token_type": "bearer"}

# 2. Use the token
curl /api/v1/users/me \
  -H "Authorization: Bearer eyJhbG..."
Endpoints

Scripting Guide

OpenReq uses a Python-based scripting engine with full syntax support. Write pre-request scripts to prepare your requests and post-response scripts to validate responses. Scripts run server-side with a req API.

Quick Start

Pre-request Script — Login & set auth header

# Login and set the Authorization header automatically
resp = req.sendRequest(
    url="http://localhost:8000/api/v1/auth/login",
    method="POST",
    json={"email": "user@example.com", "password": "secret"}
)
req.request.headers["Authorization"] = f"Bearer {resp.json.access_token}"
print("Token set!")

Post-response Script — Validate response

# Check status and extract data
req.test("Status is 200", req.response.status == 200)
req.test("Valid JSON", req.response.json is not None)
req.test("Fast response", req.response.time < 500)

# Works with both objects and arrays
data = req.response.json
if isinstance(data, list):
    req.test("Has items", len(data) > 0)
    req.variables.set("first_id", data[0].id)
else:
    req.test("Has data", data.data is not None)

req API Reference

Variables

Variables set with req.variables.set() are automatically resolved as {{key}} in the request URL, headers, body, and query parameters.

MethodDescription
req.variables.set(key, value)Set a variable (auto-resolves as {{key}})
req.variables.get(key)Get a variable value
req.variables.has(key)Check if variable exists
req.variables.unset(key)Remove a variable
req.variables.clear()Remove all variables
req.variables.toObject()Get all variables as dict
req.globals.set(key, value)Set a global variable (persists to workspace DB)
req.globals.get(key)Get a global variable
req.globals.has(key)Check if global variable exists
req.globals.unset(key)Remove a global variable
req.globals.clear()Remove all global variables
req.globals.toObject()Get all globals as dict

Variable persistence: Variables set with req.globals.set() are persisted to the workspace database — they survive across requests, collection runs, and page reloads. Use req.variables.set() for request-scoped variables that reset after each run.

Request Manipulation (Pre-request only)

Read and modify the outgoing request before it's sent:

Property / MethodDescription
req.request.urlRead/write the request URL
req.request.methodRead/write the HTTP method (GET, POST, etc.)
req.request.headers["Key"] = "val"Set a request header
req.request.bodyRead/write the request body string
req.request.query_params["k"] = "v"Set a query parameter
req.request.add_header(key, val)Add a header
req.request.remove_header(key)Remove a header
req.request.add_query_param(k, v)Add a query parameter
req.request.remove_query_param(k)Remove a query parameter

Response Access (Post-response only)

PropertyDescription
req.response.statusHTTP status code (int)
req.response.bodyRaw response body (string)
req.response.jsonParsed JSON with attribute access (e.g. req.response.json.data.id)
req.response.headers["Key"]Response header value
req.response.timeResponse time in milliseconds
req.response.text()Raw response body as string (alias for .body)

Safe access: Missing JSON fields return None instead of crashing. Both dict and array responses support attribute-style access: req.response.json[0].id works for arrays, req.response.json.data.name for objects.

Testing & Assertions

MethodDescription
req.test("name", expr)Test assertion — pass bool or callable
req.expect(val).to_equal(x)Assert equality
req.expect(val).to_include(x)Assert containment
req.expect(val).to_have_length(n)Assert length
req.expect(val).to_be_above(n)Assert greater than
req.expect(val).to_be_below(n)Assert less than
req.expect(val).to_be_a("string")Type check (string/number/boolean/object/array)
req.expect(val).to_be_true()Assert True
req.expect(val).to_be_false()Assert False
req.expect(val).to_be_none()Assert None
req.expect(val).to_not_equal(x)Assert not equal
req.expect(val).to_not_be_none()Assert not None
req.expect(val).to_exist()Assert exists (not None)
req.expect(val).to_have_property("key")Assert has property/key
req.expect(val).to_match("regex")Assert matches regex pattern

Note: req.expect() assertions auto-raise on failure. Use req.test("name", lambda: req.expect(...).to_equal(...)) to catch errors gracefully — if the expression crashes, the test is marked as FAIL instead of stopping the script.

HTTP Requests from Scripts

# Keyword style (recommended)
resp = req.sendRequest(
    url="https://api.example.com/data",
    method="POST",
    json={"key": "value"},
    headers={"Authorization": "Bearer token"}
)
print(resp.status, resp.json)

# Postman-compatible dict style
resp = req.sendRequest({
    "url": "https://api.example.com/data",
    "method": "GET",
    "header": [{"key": "Accept", "value": "application/json"}]
})

Logging

print() and req.log() both output to the Console panel.

Available Builtins

Modules: json, re, time

Functions: len, str, int, float, bool, list, dict, tuple, set, type, isinstance, issubclass, abs, min, max, sum, round, sorted, reversed, enumerate, range, zip, map, filter, any, all, hasattr, getattr, print

Syntax: Full Python — if/elif/else, for/while, try/except, list comprehensions, f-strings, function definitions, classes.

Pre-request Script Examples

Set dynamic timestamp

import time
req.variables.set("timestamp", str(int(time.time())))
req.variables.set("request_id", str(time.time_ns()))

Generate HMAC signature

import json, time
body = req.request.body or ""
ts = str(int(time.time()))
req.request.headers["X-Timestamp"] = ts
req.request.headers["X-Signature"] = str(hash(body + ts))
print(f"Signed request at {ts}")

Chain API calls — Login, then fetch user

# Step 1: Login
auth = req.sendRequest(
    url="http://localhost:8000/api/v1/auth/login",
    method="POST",
    json={"email": "admin@test.com", "password": "pass123"}
)
token = auth.json.access_token

# Step 2: Set the header for the actual request
req.request.headers["Authorization"] = f"Bearer {token}"

# Step 3: Also save for later requests
req.variables.set("token", token)
print(f"Authenticated: {token[:20]}...")

Modify URL and method dynamically

# Redirect to a different endpoint based on a variable
env = req.variables.get("environment", "dev")
if env == "production":
    req.request.url = "https://api.prod.example.com/data"
else:
    req.request.url = "https://api.dev.example.com/data"
print(f"Target: {req.request.url}")

Post-response Script Examples

Complete validation suite

# Status check
req.test("Status is 200", req.response.status == 200)

# JSON structure — safe for both array and object responses
data = req.response.json
req.test("Valid JSON", data is not None)
req.test("Is a list", isinstance(data, list))
req.test("Has items", len(data) > 0)

# Check each item has required fields
for i, item in enumerate(data):
    req.test(f"Item {i} has id", item.id is not None)
    req.test(f"Item {i} has name", item.name is not None)

# Performance
req.test("Response under 500ms", req.response.time < 500)

# Extract for next request
req.variables.set("total", str(len(data)))
print(f"Found {len(data)} items")

Using req.expect() chain

req.test("Status OK", lambda: req.expect(req.response.status).to_equal(200))
req.test("Is JSON array", lambda: req.expect(req.response.json).to_be_a("array"))
req.test("Has items", lambda: req.expect(req.response.json).to_have_length(5))
req.test("Contains admin", lambda: req.expect(req.response.body).to_include("admin"))
req.test("Name matches", lambda: req.expect(req.response.json[0].name).to_match("^[A-Z]"))

Collection-level Scripts

You can set scripts on a collection that run for every request in that collection.

  • Collection pre-request runs before the request-level pre-request script
  • Collection post-response runs before the request-level post-response script
  • Variables persist across requests in a Collection Run

Set collection scripts in the collection detail view under the "Pre-request Script" and "Tests" tabs.

Execution Order

1 Collection pre-request script
2 Request pre-request script
3 Variable resolution ({{key}} → value)
4 Auth applied (request-level > collection-level)
5 HTTP request sent
6 Collection post-response script
7 Request post-response script

JavaScript Support

OpenReq also supports JavaScript-style scripts that are transpiled to Python before execution. Basic JS syntax works:

  • let/const/var declarations (stripped during transpilation)
  • ===/!====/!=
  • console.log()req.log()
  • true/false/nullTrue/False/None
  • Template literals, ternary operators, common built-in methods

Recommendation: For complex scripts (loops, conditionals, multiple API calls), use Python mode for the best reliability.

Szkript Útmutató

Az OpenReq Python-alapú szkriptmotort használ teljes szintaxis támogatással. Írj pre-request szkripteket a kérések előkészítéséhez és post-response szkripteket a válaszok validálásához. A szkriptek szerveroldalon futnak egy req API-val.

Gyors Start

Pre-request szkript — Bejelentkezés és auth header

# Bejelentkezés és az Authorization header automatikus beállítása
resp = req.sendRequest(
    url="http://localhost:8000/api/v1/auth/login",
    method="POST",
    json={"email": "user@example.com", "password": "secret"}
)
req.request.headers["Authorization"] = f"Bearer {resp.json.access_token}"
print("Token beállítva!")

Post-response szkript — Válasz validálás

# Státusz és adatok ellenőrzése
req.test("Státusz 200", req.response.status == 200)
req.test("Érvényes JSON", req.response.json is not None)
req.test("Gyors válasz", req.response.time < 500)

# Objektumokkal és tömbökkel is működik
data = req.response.json
if isinstance(data, list):
    req.test("Van elem", len(data) > 0)
    req.variables.set("first_id", data[0].id)
else:
    req.test("Van adat", data.data is not None)

req API Referencia

Változók

A req.variables.set()-tel beállított változók automatikusan feloldódnak mint {{key}} az URL-ben, headerekben, bodyban és query paraméterekben.

MetódusLeírás
req.variables.set(key, value)Változó beállítása (auto-feloldás: {{key}})
req.variables.get(key)Változó értékének lekérése
req.variables.has(key)Létezik-e a változó
req.variables.unset(key)Változó törlése
req.variables.clear()Összes változó törlése
req.variables.toObject()Összes változó dict-ként
req.globals.set(key, value)Globális változó beállítása (workspace DB-be ment)
req.globals.get(key)Globális változó lekérése
req.globals.has(key)Létezik-e a globális változó
req.globals.unset(key)Globális változó törlése
req.globals.clear()Összes globális változó törlése
req.globals.toObject()Összes globális változó dict-ként

Változó perzisztencia: A req.globals.set()-tel beállított értékek a workspace adatbázisba mentődnek — megmaradnak kérések, kollekció futtatások és oldalfrissítés után is. Használd a req.variables.set()-et kérés-szintű változókhoz.

Kérés Módosítása (csak pre-request)

Tulajdonság / MetódusLeírás
req.request.urlURL olvasása/írása
req.request.methodHTTP metódus olvasása/írása
req.request.headers["Key"] = "val"Header beállítása
req.request.bodyBody olvasása/írása
req.request.query_params["k"] = "v"Query paraméter beállítása
req.request.add_header(key, val)Header hozzáadása
req.request.remove_header(key)Header eltávolítása
req.request.add_query_param(k, v)Query paraméter hozzáadása
req.request.remove_query_param(k)Query paraméter eltávolítása

Válasz Hozzáférés (csak post-response)

TulajdonságLeírás
req.response.statusHTTP státusz kód (int)
req.response.bodyNyers válasz body (string)
req.response.jsonParsolt JSON attribútum-stílusú hozzáféréssel
req.response.headers["Key"]Válasz header érték
req.response.timeVálaszidő milliszekundumban
req.response.text()Nyers válasz body stringként (alias a .body-hoz)

Biztonságos hozzáférés: A hiányzó JSON mezők None-t adnak vissza crash helyett. Mind a dict, mind az array válaszok támogatják az attribútum-stílusú hozzáférést: req.response.json[0].id tömbökhöz, req.response.json.data.name objektumokhoz.

Tesztelés

MetódusLeírás
req.test("név", kifejezés)Teszt assert — bool vagy callable
req.expect(val).to_equal(x)Egyenlőség ellenőrzés
req.expect(val).to_include(x)Tartalmazás ellenőrzés
req.expect(val).to_have_length(n)Hossz ellenőrzés
req.expect(val).to_be_above(n)Nagyobb mint
req.expect(val).to_be_below(n)Kisebb mint
req.expect(val).to_be_a("string")Típus ellenőrzés
req.expect(val).to_be_true()True ellenőrzés
req.expect(val).to_be_false()False ellenőrzés
req.expect(val).to_be_none()None ellenőrzés
req.expect(val).to_not_equal(x)Nem egyenlő
req.expect(val).to_not_be_none()Nem None
req.expect(val).to_exist()Létezik (nem None)
req.expect(val).to_have_property("key")Van ilyen property/kulcs
req.expect(val).to_match("regex")Regex minta illeszkedik

Megjegyzés: A req.expect() assertek automatikusan hibát dobnak ha nem teljesülnek. Használd a req.test("név", lambda: req.expect(...).to_equal(...)) formát a biztonságos futtatáshoz — ha a kifejezés hibázik, a teszt FAIL-ként jelenik meg ahelyett, hogy a script megállna.

HTTP Kérések Szkriptből

resp = req.sendRequest(
    url="https://api.example.com/data",
    method="POST",
    json={"key": "value"},
    headers={"Authorization": "Bearer token"}
)
print(resp.status, resp.json)

Elérhető Beépített Funkciók

Modulok: json, re, time

Függvények: len, str, int, float, bool, list, dict, tuple, set, type, isinstance, abs, min, max, sum, round, sorted, enumerate, range, zip, map, filter, any, all, hasattr, getattr, print

Szintaxis: Teljes Python — if/elif/else, for/while, try/except, list comprehension, f-string, függvény definíció.

Kollekció-szintű Szkriptek

Beállíthatsz szkripteket egy kollekcióhoz, amik a kollekció minden kérés esetén lefutnak.

  • Kollekció pre-request a kérés-szintű pre-request szkript ELŐTT fut
  • Kollekció post-response a kérés-szintű post-response szkript ELŐTT fut
  • A változók megőrződnek a Kollekció Futtatáson belül a kérések között

Végrehajtási Sorrend

1 Kollekció pre-request szkript
2 Kérés pre-request szkript
3 Változó feloldás ({{key}} → érték)
4 Auth alkalmazása (kérés-szint > kollekció-szint)
5 HTTP kérés elküldése
6 Kollekció post-response szkript
7 Kérés post-response szkript

JavaScript Támogatás

Az OpenReq JavaScript-stílusú szkripteket is támogat, amelyeket Python-ra transzpilál. Az alap JS szintaxis működik (let/const, ===, console.log, template literal, stb.).

Ajánlat: Összetett szkripteknél (ciklusok, feltételkezelések, több API hívás) használd a Python módot a legjobb megbízhatóság érdekében.

Scripting-Leitfaden

OpenReq verwendet eine Python-basierte Scripting-Engine mit voller Syntax-Unterstutzung. Schreiben Sie Pre-Request-Skripte zur Vorbereitung Ihrer Anfragen und Post-Response-Skripte zur Validierung der Antworten. Die Skripte laufen serverseitig mit einer req-API.

Schnellstart

Pre-Request-Skript — Login & Auth-Header

# Login und Authorization-Header automatisch setzen
resp = req.sendRequest(
    url="http://localhost:8000/api/v1/auth/login",
    method="POST",
    json={"email": "user@example.com", "password": "secret"}
)
req.request.headers["Authorization"] = f"Bearer {resp.json.access_token}"
print("Token gesetzt!")

Post-Response-Skript — Antwort validieren

# Status und Daten pruefen
req.test("Status ist 200", req.response.status == 200)
req.test("Gueltiges JSON", req.response.json is not None)
req.test("Schnelle Antwort", req.response.time < 500)

# Funktioniert mit Objekten und Arrays
data = req.response.json
if isinstance(data, list):
    req.test("Hat Elemente", len(data) > 0)
    req.variables.set("first_id", data[0].id)
else:
    req.test("Hat Daten", data.data is not None)

req-API-Referenz

Variablen

Mit req.variables.set() gesetzte Variablen werden automatisch als {{key}} in URL, Headern, Body und Query-Parametern aufgeloest.

MethodeBeschreibung
req.variables.set(key, value)Variable setzen (Auto-Aufloesung: {{key}})
req.variables.get(key)Variablenwert abrufen
req.variables.has(key)Pruefen ob Variable existiert
req.variables.unset(key)Variable entfernen
req.variables.clear()Alle Variablen entfernen
req.variables.toObject()Alle Variablen als Dict
req.globals.set(key, value)Globale Variable setzen (wird in Workspace-DB gespeichert)
req.globals.get(key)Globale Variable abrufen
req.globals.has(key)Pruefen ob globale Variable existiert
req.globals.unset(key)Globale Variable entfernen
req.globals.clear()Alle globalen Variablen entfernen
req.globals.toObject()Alle globalen Variablen als Dict

Variablen-Persistenz: Mit req.globals.set() gesetzte Werte werden in der Workspace-Datenbank gespeichert — sie bleiben ueber Anfragen, Sammlungslaeufe und Seitenaktualisierungen hinweg erhalten. Verwenden Sie req.variables.set() fuer anfragespezifische Variablen.

Anfrage-Manipulation (nur Pre-Request)

Eigenschaft / MethodeBeschreibung
req.request.urlURL lesen/schreiben
req.request.methodHTTP-Methode lesen/schreiben
req.request.headers["Key"] = "val"Header setzen
req.request.bodyBody lesen/schreiben
req.request.query_params["k"] = "v"Query-Parameter setzen
req.request.add_header(key, val)Header hinzufuegen
req.request.remove_header(key)Header entfernen
req.request.add_query_param(k, v)Query-Parameter hinzufuegen
req.request.remove_query_param(k)Query-Parameter entfernen

Antwort-Zugriff (nur Post-Response)

EigenschaftBeschreibung
req.response.statusHTTP-Statuscode (int)
req.response.bodyRoher Antwort-Body (String)
req.response.jsonGeparstes JSON mit Attribut-Zugriff
req.response.headers["Key"]Antwort-Header-Wert
req.response.timeAntwortzeit in Millisekunden
req.response.text()Roher Antwort-Body als String (Alias fuer .body)

Sicherer Zugriff: Fehlende JSON-Felder geben None zurueck, anstatt abzustuerzen. Sowohl Dict- als auch Array-Antworten unterstuetzen Attribut-Zugriff: req.response.json[0].id fuer Arrays, req.response.json.data.name fuer Objekte.

Testen

MethodeBeschreibung
req.test("Name", Ausdruck)Test-Assertion — bool oder callable
req.expect(val).to_equal(x)Gleichheit pruefen
req.expect(val).to_include(x)Enthaltensein pruefen
req.expect(val).to_have_length(n)Laenge pruefen
req.expect(val).to_be_above(n)Groesser als
req.expect(val).to_be_below(n)Kleiner als
req.expect(val).to_be_a("string")Typ pruefen
req.expect(val).to_be_true()True pruefen
req.expect(val).to_be_false()False pruefen
req.expect(val).to_be_none()None pruefen
req.expect(val).to_not_equal(x)Ungleichheit pruefen
req.expect(val).to_not_be_none()Nicht None pruefen
req.expect(val).to_exist()Existiert (nicht None)
req.expect(val).to_have_property("key")Hat Eigenschaft/Schluessel
req.expect(val).to_match("regex")Regex-Muster pruefen

Hinweis: req.expect()-Assertions loesen bei Fehlschlag automatisch einen Fehler aus. Verwenden Sie req.test("Name", lambda: req.expect(...).to_equal(...)) fuer sicheres Testen — bei einem Fehler wird der Test als FAIL markiert, anstatt das Skript zu stoppen.

Verfuegbare Builtins

Module: json, re, time

Funktionen: len, str, int, float, bool, list, dict, tuple, set, type, isinstance, abs, min, max, sum, round, sorted, enumerate, range, zip, map, filter, any, all, hasattr, getattr, print

Syntax: Volles Python — if/elif/else, for/while, try/except, List Comprehensions, f-Strings, Funktionsdefinitionen.

HTTP-Anfragen aus Skripten

resp = req.sendRequest(
    url="https://api.example.com/data",
    method="POST",
    json={"key": "value"},
    headers={"Authorization": "Bearer token"}
)
print(resp.status, resp.json)

Sammlungs-Skripte

Sie koennen Skripte auf einer Sammlung festlegen, die fuer jede Anfrage in dieser Sammlung ausgefuehrt werden.

  • Sammlungs-Pre-Request laeuft VOR dem anfragespezifischen Pre-Request-Skript
  • Sammlungs-Post-Response laeuft VOR dem anfragespezifischen Post-Response-Skript
  • Variablen bleiben waehrend eines Sammlungslaufs zwischen Anfragen erhalten

Ausfuehrungsreihenfolge

1 Sammlungs-Pre-Request-Skript
2 Anfrage-Pre-Request-Skript
3 Variablen-Aufloesung ({{key}} → Wert)
4 Auth angewendet (Anfrage > Sammlung)
5 HTTP-Anfrage gesendet
6 Sammlungs-Post-Response-Skript
7 Anfrage-Post-Response-Skript

JavaScript-Unterstutzung

OpenReq unterstuetzt auch JavaScript-Skripte, die zu Python transpiliert werden. Grundlegende JS-Syntax funktioniert (let/const, ===, console.log, Template-Literale usw.).

Empfehlung: Fuer komplexe Skripte (Schleifen, Bedingungen, mehrere API-Aufrufe) verwenden Sie den Python-Modus fuer die beste Zuverlaessigkeit.