Getting started

Introduction

Build OpenAPI documents in PHP with immutable objects, and write them for OpenAPI 3.0, 3.1 or 3.2.

OpenAPI Writer builds OpenAPI documents with PHP objects, and writes them as JSON, YAML or a PHP array for the version you choose: 3.0.0 to 3.0.4, 3.1.0 to 3.1.2, or 3.2.0. It does not depend on any framework: a script, a command, a Symfony or Laravel application, or another library can use it.

PHP
use Ark4ne\OpenApiWriter\Objects\Schema;

$book = Schema::object('Book')
    ->properties(
        Schema::integer('id')->readOnly(),
        Schema::string('title'),
        Schema::string('subtitle')->nullable(),
    )
    ->required('id', 'title');
components.schemas.Book (3.1.2)
{
  "type": "object",
  "required": ["id", "title"],
  "properties": {
    "id": { "type": "integer", "readOnly": true },
    "title": { "type": "string" },
    "subtitle": { "type": ["string", "null"] }
  }
}

The same object written for 3.0.4 gives "subtitle": { "type": "string", "nullable": true }: you describe the API once, and the library writes what each version expects.

How it works

  • One object per specification object: Schema, Operation, Response… with one method per field, named exactly like the specification. See The object model.
  • Immutable: every method returns a modified copy, so a schema or a response can be shared and derived without side effects.
  • The version is chosen when writing: the differences are converted, and a feature the version cannot express throws, or is dropped and reported in lenient mode.
  • Any object can be written: toJson(), toYaml() and toArray() work on a single schema as well as on the document. See Writing a document.
  • Validation: the validator checks the written document against the official schema of its version and ten semantic rules.

What it does not do

OpenAPI Writer writes documents; it does not read or parse OpenAPI files, scan PHP code, resolve external $ref, or validate HTTP traffic. To generate the documents of a Laravel application from its routes, form requests and resources, use the generator built on this library:

Laravel OpenAPI Generator
Generates OpenAPI 3.0, 3.1 and 3.2 documents from a Laravel application, its routes, form requests and resources.
v1.2.0ark4ne/laravel-openapi-generator

Compatibility

VersionPHPStatus
1.x^8.2Active

The only runtime requirement is ext-json. YAML output and the validation against the official schemas use optional packages; see Installation.

Next

Install the package, then follow the quick start.