Getting started

Quick start

Build a small document, write it for OpenAPI 3.1 and 3.0, and validate it.

This page builds a document with one endpoint, GET /books/{id}, writes it as JSON for two versions, and checks it.

Build the document

openapi.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Ark4ne\OpenApiWriter\Objects\Components;
use Ark4ne\OpenApiWriter\Objects\Info;
use Ark4ne\OpenApiWriter\Objects\MediaType;
use Ark4ne\OpenApiWriter\Objects\OpenApi;
use Ark4ne\OpenApiWriter\Objects\Operation;
use Ark4ne\OpenApiWriter\Objects\Parameter;
use Ark4ne\OpenApiWriter\Objects\PathItem;
use Ark4ne\OpenApiWriter\Objects\Response;
use Ark4ne\OpenApiWriter\Objects\Schema;

$openApi = OpenApi::create()
    ->info(Info::create()->title('Books API')->version('1.0.0'))
    ->paths(
        PathItem::create('/books/{id}')
            ->parameters(
                Parameter::path('id')->schema(Schema::integer()),
            )
            ->operations(
                Operation::get()
                    ->operationId('books.show')
                    ->responses(
                        Response::ok()->content(
                            MediaType::json()->schema(Schema::ref('Book')),
                        ),
                        Response::notFound(),
                    ),
            ),
    )
    ->components(
        Components::create()->schemas(
            Schema::object('Book')
                ->properties(
                    Schema::integer('id')->readOnly(),
                    Schema::string('title'),
                    Schema::string('subtitle')->nullable(),
                )
                ->required('id', 'title'),
        ),
    );

Three things to notice:

  • The first argument of create() and of the shortcuts is the key of the object in its parent: the path /books/{id}, the component name Book, the property names id, title, subtitle.
  • The shortcuts fill in the obvious: Parameter::path() sets in: path and required: true, Operation::get() places the operation under get, Response::ok() is the 200 response with the description OK.
  • Schema::ref('Book') writes {"$ref": "#/components/schemas/Book"}.

Write it

openapi.php
use Ark4ne\OpenApiWriter\Enums\Version;

file_put_contents(
    __DIR__ . '/openapi.json',
    $openApi->toJson(Version::V3_1_2, JSON_PRETTY_PRINT),
);
toJson(Version::V3_1_2)
$openApi->toJson(Version::V3_1_2, JSON_PRETTY_PRINT);
openapi.json
{
  "openapi": "3.1.2",
  "info": { "title": "Books API", "version": "1.0.0" },
  "paths": {
    "/books/{id}": {
      "get": {
        "operationId": "books.show",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/Book" }
              }
            }
          },
          "404": { "description": "Not Found" }
        }
      },
      "parameters": [
        {
          "name": "id",
          "in": "path",
          "required": true,
          "schema": { "type": "integer" }
        }
      ]
    }
  },
  "components": {
    "schemas": {
      "Book": {
        "type": "object",
        "required": ["id", "title"],
        "properties": {
          "id": { "type": "integer", "readOnly": true },
          "title": { "type": "string" },
          "subtitle": { "type": ["string", "null"] }
        }
      }
    }
  }
}

The keys follow the order of the specification, not the order of the calls.

Write it for OpenAPI 3.0

The same object, another version:

toJson(Version::V3_0_4)
$openApi->toJson(Version::V3_0_4, JSON_PRETTY_PRINT);
components.schemas.Book.properties.subtitle
{ "type": "string", "nullable": true }

Everything else is identical, except "openapi": "3.0.4". See Conversions for every difference the library handles.

Validate it

With opis/json-schema installed:

openapi.php
use Ark4ne\OpenApiWriter\Validation\OpisJsonSchemaValidator;
use Ark4ne\OpenApiWriter\Validation\Validator;

$violations = Validator::create(new OpisJsonSchemaValidator())
    ->validate($openApi);

var_dump(array_map('strval', $violations->all()));
// array(0) {}

Remove the Parameter::path('id') and the validator reports it:

[error] /paths/~1books~1{id}/get: /paths/~1books~1{id}/get has no required
in: path parameter for {id} (PathParametersRule)

Next