0
# OpenAPI3 Parser
1
2
A comprehensive Python library for parsing OpenAPI 3.0 specification documents into structured Python objects that can be programmatically accessed and manipulated. The library transforms YAML or JSON OpenAPI specifications into typed dataclass instances, providing a pythonic interface for working with API definitions.
3
4
## Package Information
5
6
- **Package Name**: openapi3-parser
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install openapi3-parser`
10
11
## Core Imports
12
13
```python
14
from openapi_parser import parse
15
```
16
17
Direct imports for specific components:
18
19
```python
20
from openapi_parser.specification import (
21
Specification, Info, Contact, License, Server, ExternalDoc, Tag,
22
Schema, Integer, Number, String, Boolean, Null, Array, Object,
23
OneOf, AnyOf, Property, Discriminator, Path, Operation, Parameter,
24
RequestBody, Response, Content, Header, Security, OAuthFlow
25
)
26
27
from openapi_parser.enumeration import (
28
DataType, IntegerFormat, NumberFormat, StringFormat, OperationMethod,
29
ParameterLocation, BaseLocation, ContentType, SecurityType,
30
AuthenticationScheme, OAuthFlowType, PathParameterStyle,
31
QueryParameterStyle, HeaderParameterStyle, CookieParameterStyle
32
)
33
34
from openapi_parser.errors import ParserError
35
```
36
37
## Basic Usage
38
39
```python
40
from openapi_parser import parse
41
42
# Parse from file
43
specification = parse('swagger.yml')
44
45
# Parse from URL
46
specification = parse('https://api.example.com/openapi.json')
47
48
# Parse from string
49
spec_content = """
50
openapi: 3.0.0
51
info:
52
title: Sample API
53
version: 1.0.0
54
paths:
55
/users:
56
get:
57
summary: Get users
58
responses:
59
'200':
60
description: Success
61
"""
62
specification = parse(spec_string=spec_content)
63
64
# Work with parsed specification
65
print(f"API Title: {specification.info.title}")
66
print(f"API Version: {specification.info.version}")
67
68
# Access servers
69
for server in specification.servers:
70
print(f"Server: {server.description} - {server.url}")
71
72
# Access paths and operations
73
for path in specification.paths:
74
methods = ','.join([op.method.value for op in path.operations])
75
print(f"Path: {path.url}, Methods: {methods}")
76
```
77
78
## Architecture
79
80
The parser transforms OpenAPI specifications into a hierarchical structure of Python dataclasses:
81
82
- **Specification**: Root container for the entire API definition
83
- **Info/Server/Tag**: Metadata and server configuration
84
- **Path/Operation**: API endpoints and HTTP operations
85
- **Schema Types**: Data model definitions (String, Integer, Object, Array, etc.)
86
- **Parameter/RequestBody/Response**: Operation input/output specifications
87
- **Security**: Authentication and authorization schemes
88
89
This structure closely mirrors the OpenAPI 3.0 specification while providing type safety and IDE support through comprehensive type hints.
90
91
## Capabilities
92
93
### Core Parsing
94
95
Main parsing functionality that transforms OpenAPI specification documents into structured Python objects.
96
97
```python { .api }
98
def parse(
99
uri: Optional[str] = None,
100
spec_string: Optional[str] = None,
101
strict_enum: bool = True
102
) -> Specification
103
```
104
105
[Core Parsing](./core-parsing.md)
106
107
### Specification Structure
108
109
The root specification object and core metadata components including API information, servers, and documentation.
110
111
```python { .api }
112
@dataclass
113
class Specification:
114
version: str
115
info: Info
116
servers: Optional[list[Server]] = None
117
paths: Optional[list[Path]] = None
118
security: Optional[list[dict]] = None
119
tags: Optional[list[Tag]] = None
120
external_docs: Optional[ExternalDoc] = None
121
security_schemas: Optional[dict[str, Security]] = None
122
schemas: Optional[dict[str, Schema]] = None
123
124
@dataclass
125
class Info:
126
title: str
127
version: str
128
description: Optional[str] = None
129
terms_of_service: Optional[str] = None
130
contact: Optional[Contact] = None
131
license: Optional[License] = None
132
```
133
134
[Specification Structure](./specification-structure.md)
135
136
### Schema System
137
138
Comprehensive schema type system for defining data models, validation rules, and type constraints.
139
140
```python { .api }
141
@dataclass
142
class Schema:
143
type: DataType
144
title: Optional[str] = None
145
description: Optional[str] = None
146
nullable: Optional[bool] = False
147
read_only: Optional[bool] = False
148
write_only: Optional[bool] = False
149
150
@dataclass
151
class Object(Schema):
152
properties: Optional[dict[str, Property]] = None
153
required: Optional[list[str]] = None
154
additional_properties: Optional[Union[bool, Schema]] = None
155
```
156
157
[Schema System](./schema-system.md)
158
159
### Operations and Paths
160
161
API endpoint definitions with HTTP operations, parameters, request bodies, and responses.
162
163
```python { .api }
164
@dataclass
165
class Path:
166
url: str
167
operations: list[Operation]
168
parameters: Optional[list[Parameter]] = None
169
summary: Optional[str] = None
170
description: Optional[str] = None
171
172
@dataclass
173
class Operation:
174
method: OperationMethod
175
responses: list[Response]
176
operation_id: Optional[str] = None
177
summary: Optional[str] = None
178
description: Optional[str] = None
179
parameters: Optional[list[Parameter]] = None
180
request_body: Optional[RequestBody] = None
181
```
182
183
[Operations and Paths](./operations-and-paths.md)
184
185
### Type System and Enums
186
187
Enumeration types and validation constraints that define allowed values for various OpenAPI specification fields.
188
189
```python { .api }
190
class DataType(Enum):
191
NULL = "null"
192
INTEGER = "integer"
193
NUMBER = "number"
194
STRING = "string"
195
BOOLEAN = "boolean"
196
ARRAY = "array"
197
OBJECT = "object"
198
ONE_OF = "oneOf"
199
ANY_OF = "anyOf"
200
201
class OperationMethod(Enum):
202
GET = "get"
203
POST = "post"
204
PUT = "put"
205
DELETE = "delete"
206
PATCH = "patch"
207
HEAD = "head"
208
OPTIONS = "options"
209
TRACE = "trace"
210
```
211
212
[Type System and Enums](./type-system-and-enums.md)
213
214
### Security System
215
216
Authentication and authorization scheme definitions including API keys, HTTP authentication, OAuth 2.0 flows, and OpenID Connect configurations.
217
218
```python { .api }
219
@dataclass
220
class Security:
221
type: SecurityType
222
location: Optional[BaseLocation] = None
223
description: Optional[str] = None
224
name: Optional[str] = None
225
scheme: Optional[AuthenticationScheme] = None
226
bearer_format: Optional[str] = None
227
flows: dict[OAuthFlowType, OAuthFlow] = field(default_factory=dict)
228
url: Optional[str] = None
229
230
@dataclass
231
class OAuthFlow:
232
refresh_url: Optional[str] = None
233
authorization_url: Optional[str] = None
234
token_url: Optional[str] = None
235
scopes: dict[str, str] = field(default_factory=dict)
236
```
237
238
[Security System](./security-system.md)
239
240
## Error Handling
241
242
```python { .api }
243
class ParserError(Exception):
244
"""Base exception for all parsing errors"""
245
```
246
247
The parser raises `ParserError` for invalid OpenAPI specifications, including missing required fields, invalid schema structures, or unsupported OpenAPI versions.