OpenAPI Specifications
This guide covers how to prepare, validate, and optimize OpenAPI specifications for effective testing with Dochia. Learn about spec requirements, common issues, and best practices for maximizing test coverage and reliability.
Overview
Dochia relies heavily on your OpenAPI specification to understand your API structure and generate comprehensive tests. The quality and completeness of your OpenAPI spec directly impacts:
- Test Coverage - More detailed specs enable more thorough testing
- Test Accuracy - Precise schemas prevent false positives/negatives
- Error Detection - Well-defined responses help identify real issues
- Test Efficiency - Optimized specs reduce unnecessary test variations
OpenAPI Specification Requirements
Supported Versions
Dochia supports OpenAPI specifications in multiple formats:
- OpenAPI 3.0.x - Recommended for new APIs
- OpenAPI 3.1.x - Full support with JSON Schema enhancements
- Swagger 2.0 - Legacy support for existing APIs
Required Elements
For effective testing, your OpenAPI spec must include:
Essential Components:
infosection with API metadatapathswith endpoint definitions- HTTP methods (GET, POST, PUT, DELETE, etc.)
- Response definitions with status codes
- Request/response schemas
- Parameter definitions
Recommended Components:
- Security schemes
- Example values
- Error response definitions
File Formats
Dochia accepts specifications in multiple formats:
# YAML format (recommended for readability)
openapi: 3.0.3
info:
title: My API
version: 1.0.0
paths:
/users:
get:
responses:
'200':
description: Success
{
"openapi": "3.0.3",
"info": {
"title": "My API",
"version": "1.0.0"
},
"paths": {
"/users": {
"get": {
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
}
Optimizing Specs for Testing
Schema Completeness
Detailed Request Schemas:
# ❌ Minimal schema (limited test coverage)
components:
schemas:
User:
type: object
properties:
name:
type: string
# ✅ Comprehensive schema (better test coverage)
components:
schemas:
User:
type: object
required:
- name
- email
properties:
name:
type: string
minLength: 1
maxLength: 100
pattern: '^[a-zA-Z\s]+$'
email:
type: string
format: email
age:
type: integer
minimum: 0
maximum: 150
preferences:
type: object
properties:
newsletter:
type: boolean
theme:
type: string
enum: ['light', 'dark']
Response Schema Definitions:
# ✅ Well-defined response schemas
paths:
/users/{id}:
get:
responses:
'200':
description: User found
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
content:
application/json:
schema:
type: object
properties:
error:
type: string
example: "User not found"
code:
type: integer
example: 404
'500':
description: Server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Parameter Validation
Path Parameters:
paths:
/users/{userId}/posts/{postId}:
get:
parameters:
- name: userId
in: path
required: true
schema:
type: integer
minimum: 1
- name: postId
in: path
required: true
schema:
type: integer
minimum: 1
Query Parameters:
paths:
/users:
get:
parameters:
- name: page
in: query
schema:
type: integer
minimum: 1
default: 1
- name: limit
in: query
schema:
type: integer
minimum: 1
maximum: 100
default: 20
- name: sort
in: query
schema:
type: string
enum: ['name', 'created_at', 'updated_at']
- name: filter
in: query
schema:
type: string
pattern: '^[a-zA-Z0-9\s]+$'
Header Parameters:
paths:
/users:
post:
parameters:
- name: X-API-Version
in: header
required: true
schema:
type: string
enum: ['v1', 'v2']
- name: X-Request-ID
in: header
schema:
type: string
format: uuid
Security Definitions
Authentication Schemes:
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
OAuth2:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes:
read: Read access
write: Write access
# Apply security to endpoints
paths:
/users:
get:
security:
- BearerAuth: []
post:
security:
- BearerAuth: []
- ApiKeyAuth: []
/public/health:
get:
security: [] # No authentication required
Common Specification Issues
Schema Problems
Type Mismatches:
# ❌ Common type issues
components:
schemas:
User:
type: object
properties:
id:
type: string # Should be integer for numeric IDs
created_at:
type: string # Should specify format: date-time
active:
type: string # Should be boolean
tags:
type: string # Should be array for multiple values
# ✅ Correct type definitions
components:
schemas:
User:
type: object
properties:
id:
type: integer
created_at:
type: string
format: date-time
active:
type: boolean
tags:
type: array
items:
type: string
Missing Constraints:
# ❌ Unconstrained fields (poor test coverage)
components:
schemas:
User:
type: object
properties:
email:
type: string
password:
type: string
age:
type: integer
# ✅ Well-constrained fields (better testing)
components:
schemas:
User:
type: object
required:
- email
- password
properties:
email:
type: string
format: email
maxLength: 255
password:
type: string
minLength: 8
maxLength: 128
pattern: '^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)'
age:
type: integer
minimum: 13
maximum: 120
Response Definition Issues
Incomplete Error Responses:
# ❌ Missing error response definitions
paths:
/users:
post:
responses:
'201':
description: Created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
# Missing 400, 401, 403, 422, 500 responses
# ✅ Complete error response coverage
paths:
/users:
post:
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/ValidationError'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/AuthError'
'422':
description: Validation failed
content:
application/json:
schema:
$ref: '#/components/schemas/ValidationError'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ServerError'
Inconsistent Content Types:
# ❌ Inconsistent content types
paths:
/users:
get:
responses:
'200':
content:
application/json: # JSON response
schema:
type: array
items:
$ref: '#/components/schemas/User'
post:
responses:
'201':
content:
text/plain: # Inconsistent with GET
schema:
type: string
# ✅ Consistent content types
paths:
/users:
get:
responses:
'200':
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
post:
responses:
'201':
content:
application/json: # Consistent JSON
schema:
$ref: '#/components/schemas/User'
Advanced Specification Features
Using Examples Effectively
Request Examples:
paths:
/users:
post:
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUser'
examples:
valid_user:
summary: Valid user creation
value:
name: "John Doe"
email: "john@example.com"
age: 30
minimal_user:
summary: Minimal required fields
value:
name: "Jane Smith"
email: "jane@example.com"
Response Examples:
paths:
/users/{id}:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/User'
examples:
john_doe:
summary: Regular user
value:
id: 123
name: "John Doe"
email: "john@example.com"
created_at: "2024-01-15T10:30:00Z"
admin_user:
summary: Admin user
value:
id: 456
name: "Admin User"
email: "admin@example.com"
role: "admin"
created_at: "2024-01-01T00:00:00Z"
Conditional Logic
OneOf Schemas:
components:
schemas:
Pet:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
discriminator:
propertyName: petType
mapping:
cat: '#/components/schemas/Cat'
dog: '#/components/schemas/Dog'
Cat:
type: object
required:
- petType
- meowVolume
properties:
petType:
type: string
enum: ['cat']
meowVolume:
type: integer
minimum: 1
maximum: 10
Dog:
type: object
required:
- petType
- barkVolume
properties:
petType:
type: string
enum: ['dog']
barkVolume:
type: integer
minimum: 1
maximum: 10
AnyOf Schemas:
components:
schemas:
SearchResult:
anyOf:
- $ref: '#/components/schemas/User'
- $ref: '#/components/schemas/Product'
- $ref: '#/components/schemas/Article'
properties:
type:
type: string
enum: ['user', 'product', 'article']
relevance:
type: number
minimum: 0
maximum: 1
Custom Formats
Custom String Formats:
components:
schemas:
User:
type: object
properties:
phone:
type: string
format: phone # Custom format
pattern: '^\+[1-9]\d{1,14}$'
social_security:
type: string
format: ssn
pattern: '^\d{3}-\d{2}-\d{4}$'
color:
type: string
format: hex-color
pattern: '^#[0-9A-Fa-f]{6}$'
Specification Maintenance
Documentation Best Practices
Comprehensive Descriptions:
paths:
/users/{id}:
get:
summary: Retrieve user by ID
description: |
Fetches a single user by their unique identifier.
**Access Control:**
- Users can access their own profile
- Admins can access any user profile
- Public fields are returned for all authenticated users
**Rate Limiting:**
- 100 requests per minute per user
- 1000 requests per minute for admin users
parameters:
- name: id
in: path
required: true
description: Unique identifier for the user
schema:
type: integer
minimum: 1
example: 12345
Error Documentation:
components:
schemas:
ValidationError:
type: object
required:
- error
- message
- details
properties:
error:
type: string
enum: ['validation_failed']
description: Error type identifier
message:
type: string
description: Human-readable error message
example: "Validation failed for one or more fields"
details:
type: array
description: Specific validation errors
items:
type: object
properties:
field:
type: string
description: Field that failed validation
example: "email"
code:
type: string
description: Validation error code
example: "invalid_format"
message:
type: string
description: Field-specific error message
example: "Email address is not valid"
Troubleshooting Specification Issues
Common Testing Problems
Schema Validation Failures:
# Problem: Tests fail due to overly strict schemas
components:
schemas:
User:
type: object
required:
- id
- name
- email
- created_at
- updated_at
- last_login # Too strict - may be null for new users
properties:
last_login:
type: string
format: date-time # Fails when null
# Solution: Handle nullable fields
components:
schemas:
User:
type: object
required:
- id
- name
- email
- created_at
- updated_at
properties:
last_login:
type: string
format: date-time
nullable: true # Allow null values
Response Mismatch Issues:
# Problem: API returns different structure than spec
# Spec says:
components:
schemas:
UserList:
type: object
properties:
users:
type: array
items:
$ref: '#/components/schemas/User'
# But API returns:
# {
# "data": [...], // Not "users"
# "pagination": {...} // Not in spec
# }
# Solution: Update spec to match actual API response
components:
schemas:
UserList:
type: object
properties:
data: # Match actual field name
type: array
items:
$ref: '#/components/schemas/User'
pagination: # Include actual response structure
$ref: '#/components/schemas/Pagination'
Performance Considerations
Large Schema Optimization:
# Problem: Deeply nested schemas cause slow validation
components:
schemas:
DeepObject:
type: object
properties:
level1:
type: object
properties:
level2:
type: object
properties:
level3:
# ... many more levels
# Solution: Use references to break up complexity
components:
schemas:
DeepObject:
type: object
properties:
level1:
$ref: '#/components/schemas/Level1Object'
Level1Object:
type: object
properties:
level2:
$ref: '#/components/schemas/Level2Object'
Circular Reference Handling:
# Problem: Circular references in schemas
components:
schemas:
User:
type: object
properties:
id:
type: integer
friends:
type: array
items:
$ref: '#/components/schemas/User' # Circular reference
# Solution: Limit depth or use simplified references
components:
schemas:
User:
type: object
properties:
id:
type: integer
friends:
type: array
items:
$ref: '#/components/schemas/UserSummary' # Simplified reference
UserSummary:
type: object
properties:
id:
type: integer
name:
type: string
# No friends array to break circular reference
Best Practices Summary
Specification Quality
- Completeness - Define all endpoints, parameters, and responses
- Accuracy - Ensure specs match actual API behavior
- Consistency - Use consistent naming and patterns
- Validation - Include appropriate constraints and formats
- Documentation - Provide clear descriptions and examples
Testing Optimization
- Schema Depth - Balance detail with maintainability
- Error Coverage - Define all possible error responses
- Edge Cases - Include boundary conditions in constraints
- Security - Document authentication and authorization
- Examples - Provide realistic test data
Maintenance
- Version Control - Track spec changes alongside code
- Validation - Regularly validate specs against running APIs
- Updates - Keep specs current with API changes
- Reviews - Include spec reviews in development process
- Testing - Validate specs with Dochia before deployment
Next Steps
After optimizing your OpenAPI specifications, explore:
- Test Execution - Running comprehensive tests with your optimized specs
- Configuration - Advanced configuration options for spec-specific testing
- Reporting - Understanding test results and spec-related issues
- Best Practices - Advanced API testing strategies