← 返回
安全合规 中文

REST API Tester

Test REST APIs with customizable headers, authentication, and request bodies. Use when debugging API endpoints, testing authentication flows, validating resp...
测试REST API,支持自定义请求头、认证方式和请求体。用于调试API端点、测试认证流程、验证响应等场景。
leonardodpanda
安全合规 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 1
Stars
📥 1,099
下载
💾 12
安装
1
版本
#latest

概述

API Tester

Test REST APIs with custom headers, auth, and request bodies.

When to Use

  • Debugging API endpoints during development
  • Testing authentication flows
  • Validating webhook payloads
  • Checking API response times
  • Automating health checks
  • Testing third-party integrations

Quick Start

Simple GET Request

import requests

def test_get(url, headers=None):
    """Test a GET endpoint"""
    try:
        response = requests.get(url, headers=headers, timeout=30)
        return {
            'status': response.status_code,
            'headers': dict(response.headers),
            'body': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
            'time': response.elapsed.total_seconds()
        }
    except Exception as e:
        return {'error': str(e)}

# Usage
test_get('https://api.github.com/users/octocat')

POST with JSON Body

def test_post(url, data, headers=None):
    """Test POST endpoint with JSON body"""
    default_headers = {'Content-Type': 'application/json'}
    if headers:
        default_headers.update(headers)
    
    try:
        response = requests.post(
            url, 
            json=data, 
            headers=default_headers,
            timeout=30
        )
        return {
            'status': response.status_code,
            'body': response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text
        }
    except Exception as e:
        return {'error': str(e)}

# Usage
test_post('https://httpbin.org/post', {'key': 'value'})

Test with Authentication

def test_with_auth(url, token=None, username=None, password=None):
    """Test API with Bearer token or Basic auth"""
    headers = {}
    
    if token:
        headers['Authorization'] = f'Bearer {token}'
    elif username and password:
        import base64
        credentials = base64.b64encode(f'{username}:{password}'.encode()).decode()
        headers['Authorization'] = f'Basic {credentials}'
    
    return test_get(url, headers)

# Bearer token
test_with_auth('https://api.example.com/data', token='your_token_here')

# Basic auth
test_with_auth('https://api.example.com/data', username='admin', password='secret')

Full API Test Suite

def comprehensive_api_test(base_url, endpoints):
    """Test multiple endpoints"""
    results = {}
    
    for endpoint, config in endpoints.items():
        url = f"{base_url}{config['path']}"
        method = config.get('method', 'GET')
        headers = config.get('headers', {})
        data = config.get('data')
        
        try:
            if method == 'GET':
                response = requests.get(url, headers=headers, timeout=30)
            elif method == 'POST':
                response = requests.post(url, json=data, headers=headers, timeout=30)
            elif method == 'PUT':
                response = requests.put(url, json=data, headers=headers, timeout=30)
            elif method == 'DELETE':
                response = requests.delete(url, headers=headers, timeout=30)
            
            results[endpoint] = {
                'status': response.status_code,
                'success': 200 <= response.status_code < 300,
                'time': response.elapsed.total_seconds()
            }
        except Exception as e:
            results[endpoint] = {'error': str(e), 'success': False}
    
    return results

# Usage
endpoints = {
    'health': {'path': '/health', 'method': 'GET'},
    'create_user': {'path': '/users', 'method': 'POST', 'data': {'name': 'Test'}},
    'get_user': {'path': '/users/1', 'method': 'GET'}
}

comprehensive_api_test('https://api.example.com', endpoints)

Common Testing Scenarios

Webhook Testing

from flask import Flask, request

def create_webhook_listener(port=5000):
    """Create local webhook receiver for testing"""
    app = Flask(__name__)
    received_data = []
    
    @app.route('/webhook', methods=['POST'])
    def webhook():
        data = request.json
        received_data.append(data)
        print(f"Received webhook: {data}")
        return {'status': 'ok'}
    
    @app.route('/received', methods=['GET'])
    def get_received():
        return {'data': received_data}
    
    return app

# Run: app.run(port=5000)
# Use ngrok to expose: ngrok http 5000

Performance Testing

import time

def test_api_performance(url, iterations=10):
    """Test API response times"""
    times = []
    
    for _ in range(iterations):
        start = time.time()
        requests.get(url, timeout=30)
        times.append(time.time() - start)
    
    return {
        'min': min(times),
        'max': max(times),
        'avg': sum(times) / len(times),
        'times': times
    }

Response Validation

def validate_response(response, expected_status=200, required_fields=None):
    """Validate API response structure"""
    errors = []
    
    if response.get('status') != expected_status:
        errors.append(f"Expected status {expected_status}, got {response.get('status')}")
    
    body = response.get('body', {})
    if required_fields:
        for field in required_fields:
            if field not in body:
                errors.append(f"Missing required field: {field}")
    
    return {
        'valid': len(errors) == 0,
        'errors': errors
    }

Dependencies

pip install requests flask

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-03-30 03:42 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

security-compliance

OpenClaw Backup

alex3alex
备份与恢复 OpenClaw 数据。适用于创建备份、设置自动备份计划、从备份恢复或管理备份轮转。处理 ~/.openclaw 目录归档并包含适当的排除规则。
★ 89 📥 30,590
security-compliance

Skill Vetter

spclaudehome
AI智能体技能安全预审工具。安装ClawdHub、GitHub等来源技能前,检查风险信号、权限范围及可疑模式。
★ 1,211 📥 266,210
productivity

Batch File Renamer

leonardodpanda
批量重命名文件,支持强大的模式、正则表达式和预览功能。适用于整理大量文件、统一起名规范。
★ 0 📥 849