Search by

jaspr / oas-builder

allone

JSON API Open API Schema Generator

Package info

gitlab.com/jaspr/oas-builder

Issues

pkg:composer/jaspr/oas-builder

Statistics

Installs: 17 496

Dependents: 2

Suggesters: 0

Stars: 0

2.0.0 2026-10-19 23:31 UTC

This package is auto-updated.

Last update: 2026-10-19 21:33:27 UTC


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.