jaspr / oas-builder
JSON API Open API Schema Generator
Requires
- php: ^8.2
Requires (Dev)
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.5
- rector/rector: 2.0.0-rc2
- squizlabs/php_codesniffer: ^3.11
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Typed PHP objects for building an OpenAPI 3.0.3 document that
json_encode() turns into a valid specification. jaspr/mapper uses it
to describe JSON:API endpoints; you can use it on its own or add your own paths to the mapper's document.
composer require jaspr/oas-builder
PHP 8.2 or later. Upgrading from 1.x? Read UPGRADE.md.
Example
use JSONAPI\OAS\{Info, MediaType, OAuthFlow, OAuthFlows, OpenAPISpecification, Operation, Parameter, PathItem,
Response, Responses, SecurityRequirement, SecurityScheme};
use JSONAPI\OAS\Type\{DataType, In};
$oas = new OpenAPISpecification(new Info('Library API', '1.0.0'));
$components = $oas->getComponents();
$components->addSchema('Book', DataType::object()
->addProperty('title', DataType::string())
->addProperty('published', DataType::date())
->setRequired(['title']));
$components->addSecurityScheme('oauth', SecurityScheme::oauth2(
(new OAuthFlows())->setAuthorizationCode(OAuthFlow::authorizationCode(
'https://id.example.com/auth',
'https://id.example.com/token',
['read' => 'Read books']
))
));
$read = new SecurityRequirement();
$read->addRequirements('oauth', ['read']);
$oas->getPaths()->addPath('/books/{id}', (new PathItem())
->addParameter((new Parameter('id', In::PATH))->setSchema(DataType::string()))
->setGet(Operation::new()
->setOperationId('getBook')
->addSecurity($read)
->setResponses((new Responses())->addResponse('200', (new Response('A book'))->addContent(
'application/json',
(new MediaType())->setSchema($components->createSchemaReference('Book'))
)))));
echo json_encode($oas, JSON_PRETTY_PRINT);
Every object of the specification has a class of the same name (Operation, Parameter, Schema,
Link, …). Reusable objects go into Components and are referenced with its create…Reference() methods,
which refuse references to entries that do not exist. Objects whose fields exclude each other (an example
value and an external value, an operation id and an operation reference) throw on the second one.