1# php-openapi
2
3Read and write [OpenAPI](https://www.openapis.org/) 3.0.x YAML and JSON files and make the content accessible in PHP objects.
4
5It also provides a CLI tool for validating and converting OpenAPI 3.0.x Description files.
6
7[](https://packagist.org/packages/cebe/php-openapi)
8[](https://packagist.org/packages/cebe/php-openapi)
9[](https://github.com/cebe/php-openapi/actions)
10[](https://packagist.org/packages/cebe/php-openapi)
11
12
13## Install
14
15 composer require cebe/php-openapi
16
17## Requirements
18
19- PHP 7.1 or higher (works fine with PHP 8)
20
21## Used by
22
23This library provides a low level API for reading and writing OpenAPI files. It is used by higher level tools to
24do awesome work:
25
26- [cebe/yii2-openapi](https://github.com/cebe/yii2-openapi) Code Generator for REST API from OpenAPI 3 Descriptions, includes fake data generator.
27- [cebe/yii2-app-api](https://github.com/cebe/yii2-app-api) Yii framework application template for developing API-first applications.
28- [league/openapi-psr7-validator](https://github.com/thephpleague/openapi-psr7-validator) validates PSR-7 messages (HTTP request/response) against OpenAPI descriptions.
29- [dsuurlant/response2schema](https://github.com/dsuurlant/response2schema) a quick and easy tool for generating OpenAPI schemas based on example data.
30- ... ([add yours](https://github.com/cebe/php-openapi/edit/master/README.md#L24))
31
32## Usage
33
34### CLI Tool
35
36 $ vendor/bin/php-openapi help
37 PHP OpenAPI 3 tool
38 ------------------
39 by Carsten Brandt <mail@cebe.cc>
40
41 Usage:
42 php-openapi <command> [<options>] [input.yml|input.json] [output.yml|output.json]
43
44 The following commands are available:
45
46 validate Validate the API Description in the specified input file against the OpenAPI v3.0 schema.
47 Note: the validation is performed in two steps. The results are composed of
48 (1) structural errors found while reading the API Description file, and
49 (2) violations of the OpenAPI v3.0 schema.
50
51 If no input file is specified input will be read from STDIN.
52 The tool will try to auto-detect the content type of the input, but may fail
53 to do so. You may specify --read-yaml or --read-json to force the file type.
54
55 Exits with code 2 on validation errors, 1 on other errors and 0 on success.
56
57 convert Convert a JSON or YAML input file to JSON or YAML output file.
58
59 If no input file is specified input will be read from STDIN.
60 If no output file is specified output will be written to STDOUT.
61 The tool will try to auto-detect the content type of the input and output file, but may fail
62 to do so. You may specify --read-yaml or --read-json to force the input file type.
63 and --write-yaml or --write-json to force the output file type.
64
65 By default all references are resolved (replaced with the object referred to). You can control
66 handling of references with the following arguments:
67
68 --resolve-none Do not resolve references.
69 --resolve-external Only resolve references that point to external files.
70 This process is often referred to as "inlining".
71 --resolve-all Resolve all references (default).
72 Recursive pointers will stay references.
73
74 inline Convert a JSON or YAML input file to JSON or YAML output file and
75 resolve all external references. The output will be a single API Description file.
76 This is a shortcut for calling convert --resolve-external.
77
78 help Shows this usage information.
79
80 Options:
81
82 --read-json force reading input as JSON. Auto-detect if not specified.
83 --read-yaml force reading input as YAML. Auto-detect if not specified.
84 --write-json force writing output as JSON. Auto-detect if not specified.
85 --write-yaml force writing output as YAML. Auto-detect if not specified.
86 -s, --silent silent mode. Will hide all success/information messages and only print errors.
87
88
89### Reading API Description Files
90
91Read OpenAPI Description from JSON file:
92
93```php
94use cebe\openapi\Reader;
95
96// realpath is needed for resolving references with relative Paths or URLs
97$openapi = Reader::readFromJsonFile(realpath('openapi.json'));
98```
99
100Read OpenAPI Description from YAML:
101
102```php
103use cebe\openapi\Reader;
104
105// realpath is needed for resolving references with relative Paths or URLs
106$openapi = Reader::readFromYamlFile(realpath('openapi.yaml'));
107// you may also specify the URL to your API Description file
108$openapi = Reader::readFromYamlFile('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.0.2/examples/v3.0/petstore-expanded.yaml');
109```
110
111Access API Description data:
112
113```php
114echo $openapi->openapi; // openAPI version, e.g. 3.0.0
115echo $openapi->info->title; // API title
116foreach($openapi->paths as $path => $definition) {
117 // iterate path definitions
118}
119```
120
121Object properties are exactly like in the [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#openapi-specification).
122You may also access additional properties added by [specification extensions](https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#specificationExtensions).
123
124### Writing API Description Files
125
126```php
127use cebe\openapi\spec\OpenApi;
128use cebe\openapi\spec\PathItem;
129
130// create base API Description
131$openapi = new OpenApi([
132 'openapi' => '3.0.2',
133 'info' => [
134 'title' => 'Test API',
135 'version' => '1.0.0',
136 ],
137 'paths' => [],
138]);
139// manipulate description as needed
140$openapi->paths['/test'] = new PathItem([
141 'description' => 'something'
142]);
143// ...
144
145$json = \cebe\openapi\Writer::writeToJson($openapi);
146```
147
148results in the following JSON data:
149
150```json
151{
152 "openapi": "3.0.0",
153 "info": {
154 "title": "Test API",
155 "version": "1.0.0"
156 },
157 "paths": {
158 "/test": {
159 "description": "something"
160 }
161 }
162}
163```
164
165### Writing API Description Files using prepared Objects
166
167Since version 1.2.0, the above example can also be written like this (passing objects instead of arrays):
168
169```php
170use cebe\openapi\spec\OpenApi;
171use cebe\openapi\spec\PathItem;
172use cebe\openapi\spec\Info;
173
174
175// create base API Description
176$openapi = new OpenApi([
177 'openapi' => '3.0.2',
178 'info' => new Info([
179 'title' => 'Test API',
180 'version' => '1.0.0',
181 ]),
182 'paths' => [
183 '/test' => new PathItem([
184 'description' => 'something'
185 ]),
186 ],
187]);
188$json = \cebe\openapi\Writer::writeToJson($openapi);
189```
190
191### Reading API Description Files and Resolving References
192
193In the above we have passed the raw JSON or YAML data to the Reader. In order to be able to resolve
194references to structures in external files, we must provide the full context.
195
196```php
197use cebe\openapi\Reader;
198// an absolute URL or file path is needed to allow resolving external references
199$openapi = Reader::readFromJsonFile('https://www.example.com/api/openapi.json');
200$openapi = Reader::readFromYamlFile('https://www.example.com/api/openapi.yaml');
201```
202
203If data has been loaded in a different way you can manually resolve references like this by giving a context:
204
205```php
206$openapi->resolveReferences(
207 new \cebe\openapi\ReferenceContext($openapi, 'https://www.example.com/api/openapi.yaml')
208);
209```
210
211### Validation
212
213The library provides simple validation operations, that check basic OpenAPI spec requirements.
214This is the same as "structural errors found while reading the API Description file" from the CLI tool.
215This validation does not include checking against the OpenAPI v3.0 JSON schema, this is only implemented in the CLI.
216
217```
218// return `true` in case no errors have been found, `false` in case of errors.
219$specValid = $openapi->validate();
220// after validation getErrors() can be used to retrieve the list of errors found.
221$errors = $openapi->getErrors();
222```
223
224> **Note:** Validation is done on a very basic level and is not complete. So a failing validation will show some errors,
225> but the list of errors given may not be complete. Also a passing validation does not necessarily indicate a completely
226> valid spec.
227
228
229## Completeness
230
231This library is currently work in progress, the following list tracks completeness:
232
233- [x] read OpenAPI 3.0 JSON
234- [x] read OpenAPI 3.0 YAML
235- [ ] OpenAPI 3.0 Schema
236 - [x] OpenAPI Object
237 - [x] Info Object
238 - [x] Contact Object
239 - [x] License Object
240 - [x] Server Object
241 - [x] Server Variable Object
242 - [x] Components Object
243 - [x] Paths Object
244 - [x] Path Item Object
245 - [x] Operation Object
246 - [x] External Documentation Object
247 - [x] Parameter Object
248 - [x] Request Body Object
249 - [x] Media Type Object
250 - [x] Encoding Object
251 - [x] Responses Object
252 - [x] Response Object
253 - [x] Callback Object
254 - [x] Example Object
255 - [x] Link Object
256 - [ ] [Runtime Expressions](https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#runtime-expressions)
257 - [x] Header Object
258 - [x] Tag Object
259 - [x] Reference Object
260 - [x] Schema Object
261 - [x] load/read
262 - [ ] validation
263 - [x] Discriminator Object
264 - [x] XML Object
265 - [x] Security Scheme Object
266 - [x] OAuth Flows Object
267 - [x] OAuth Flow Object
268 - [x] Security Requirement Object
269
270# Support
271
272**Need help with your API project?**
273
274Professional support, consulting as well as software development services are available:
275
276https://www.cebe.cc/en/contact
277
278Development of this library is sponsored by [cebe.:cloud: "Your Professional Deployment Platform"](https://cebe.cloud).
279