File size: 7,127 Bytes
e9983a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | # API Contract Validator CLI Tool
## Objective
Create a Python CLI tool that validates API endpoints against OpenAPI/Swagger specifications by making HTTP requests and validating responses against the specification.
## Requirements
### 1. Command-Line Interface
**CRITICAL: File Structure Requirements**
The tool **MUST** be implemented as a single standalone Python script file with the following exact specifications:
1. **File Location**: The script must be located at exactly `/app/apivalidator` (absolute path)
2. **File Type**: It must be a regular file (not a directory, symlink, or package)
3. **Shebang Line**: The first line of the file must be `#!/usr/bin/env python3` (no blank lines before it)
4. **Executable Permissions**: The file must have execute permissions set (use `chmod +x /app/apivalidator`)
5. **Execution Method**: The tool must work when invoked as `python3 apivalidator <arguments>`
**Implementation Steps:**
1. Create a single Python file at `/app/apivalidator`
2. Start the file with `#!/usr/bin/env python3` as the very first line
3. Write your Python code below the shebang
4. Make the file executable: `chmod +x /app/apivalidator`
5. Ensure the script can be run with `python3 apivalidator --help` (Python will execute the file even though it's not in a package)
**Example File Structure:**
```
/app/
└── apivalidator (single Python file, executable)
```
**NOT Allowed:**
- `/app/apivalidator/` (directory)
- `/app/apivalidator.py` (different name)
- Package structure with `__init__.py`
- Multiple files or modules
**Required Arguments:**
- `--spec FILE`: Path to OpenAPI/Swagger specification file (JSON or YAML) (required)
- `--base-url URL`: Base URL of the API to test (required)
- `--output FILE`: Output file path for the validation report (required)
**Optional Arguments:**
- `--format {json,markdown,html}`: Output format (default: json)
- `--endpoints PATH`: Comma-separated list of endpoint paths to test (optional, defaults to all)
- `--methods METHOD`: Comma-separated list of HTTP methods to test (optional, defaults to all)
- `--timeout SECONDS`: Request timeout in seconds (default: 10)
- `--auth TOKEN`: Authentication token (optional, simple format: `Bearer TOKEN` or just `TOKEN`)
- `--validate-response`: Validate response payloads against schema (default: true)
- `--generate-tests`: Generate test cases for endpoints (default: false)
- `--verbose`: Enable verbose output
### 2. OpenAPI Specification Parsing
The tool must:
- Parse OpenAPI 3.0 and Swagger 2.0 specifications (both JSON and YAML formats)
- Extract all available endpoints and HTTP methods from the `paths` section
- Parse request/response schemas (JSON Schema format)
- Handle basic path parameters, query parameters, request bodies, and headers
- Extract operation information (operation IDs, descriptions, summaries)
### 3. API Contract Validation
For each endpoint, the tool must:
1. **Make HTTP Requests**: Send actual HTTP requests to the API endpoints using the base URL
2. **Validate Responses**:
- Check HTTP status codes match expected responses in the spec
- If `--validate-response` is enabled, validate response body against response schema using JSON Schema validation
3. **Report Results**: Document which endpoints passed, failed, or had errors
### 4. Output Formats
#### JSON Format
The output must be valid JSON with the following structure:
```json
{
"summary": {
"total_endpoints": 5,
"tested_endpoints": 5,
"passed": 3,
"failed": 2,
"errors": 0
},
"endpoints": [
{
"path": "/users",
"method": "GET",
"status": "passed",
"status_code": 200,
"errors": []
}
]
}
```
#### Markdown Format
Generate a Markdown report with:
- Summary section with statistics
- Endpoint-by-endpoint validation results
- Failed validations with details
#### HTML Format
Generate an HTML report with:
- Basic HTML structure (`<html>`, `<head>`, `<body>` tags)
- Summary section
- Endpoint results
### 5. Error Handling
The tool must handle errors gracefully:
- **Invalid Specification**: If the spec file cannot be parsed (invalid JSON/YAML), exit with code 1 and print error message to stderr
- **Missing Required Arguments**: If required arguments (`--spec`, `--base-url`, `--output`) are missing, exit with code 1 and print error message to stderr
- **Invalid Format**: If `--format` is not one of `json`, `markdown`, or `html`, exit with code 1 and print error message to stderr
- **Network Errors**: If HTTP requests fail (connection refused, timeout), document the error in the output but continue processing other endpoints
- **Invalid Base URL**: If the base URL is malformed, exit with code 1
**Exit Codes:**
- `0`: Success (all endpoints processed, even if some failed validation)
- `1`: Error (invalid arguments, invalid spec file, or other fatal errors)
### 6. Implementation Requirements
- Use standard Python libraries where possible
- Use `requests` library for HTTP operations
- Use `jsonschema` library for schema validation
- Parse YAML using `pyyaml` or `ruamel.yaml`
- Handle both OpenAPI 3.0 and Swagger 2.0 formats
- Provide clear, actionable error messages
- Exit with appropriate exit codes (0 for success, 1 for errors)
## Constraints
- Must validate actual HTTP endpoints (not just schema validation)
- Must handle network errors gracefully (document but don't crash)
- Must generate valid JSON/Markdown/HTML output as specified
- Must handle missing or invalid specification files
- Must validate response schemas when `--validate-response` is enabled
- Must support basic authentication via `--auth` parameter
## Example Usage
```bash
# Basic validation
python3 apivalidator --spec api-spec.yaml --base-url https://api.example.com --output report.json
# With authentication
python3 apivalidator --spec api-spec.json --base-url https://api.example.com --output report.json --auth "Bearer token123"
# Generate Markdown report
python3 apivalidator --spec api-spec.yaml --base-url https://api.example.com --output report.md --format markdown
# Generate HTML report
python3 apivalidator --spec api-spec.yaml --base-url https://api.example.com --output report.html --format html
# Filter specific endpoints
python3 apivalidator --spec api-spec.json --base-url https://api.example.com --output report.json --endpoints "/users,/posts"
# With response validation
python3 apivalidator --spec api-spec.yaml --base-url https://api.example.com --output report.json --validate-response
# Generate test cases
python3 apivalidator --spec api-spec.yaml --base-url https://api.example.com --output report.json --generate-tests
```
## Testing
Your solution will be tested by:
1. Verifying the tool exists and is executable
2. Testing help message display
3. Testing required argument validation
4. Testing OpenAPI specification parsing (JSON and YAML)
5. Testing output file generation in different formats (JSON, Markdown, HTML)
6. Testing error handling for invalid inputs
7. Testing optional parameter acceptance (timeout, auth, endpoints, methods, validate-response, generate-tests)
|