Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Openapi Specification Laravel Package

oai/openapi-specification

The OpenAPI Specification is the official, language-agnostic standard for describing RESTful APIs. It lets humans and machines discover and understand a service's capabilities without source code, docs, or traffic inspection, making it foundational for API tooling in PHP and Laravel projects.

Deep Wiki
Context7

Getting Started

This is not a Composer package — it is the source-of-truth repository for the OpenAPI Specification itself (Markdown prose, JSON Schema files, and example documents). You cannot composer require it, and there is no PHP code in it. Treat it as vendored reference material plus a machine-readable validator for the API contracts your Laravel app produces and consumes.

Minimal setup

  1. Pin a release tag rather than tracking main (the prose and schema change between releases, and main carries in-progress work):
git submodule add https://github.com/OAI/OpenAPI-Specification.git resources/openapi-spec
cd resources/openapi-spec && git checkout 3.1.1   # or whatever tag matches your tooling

A shallow copy of only what you need is usually better than a submodule:

mkdir -p resources/openapi/schemas/v3.1 resources/openapi/examples
curl -sL https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.1.1/schemas/v3.1/schema.json \
  -o resources/openapi/schemas/v3.1/schema.json
  1. Orient yourself in this order:

    • versions/3.1.0.md (or whichever minor you target) — the normative text. Skim the Path Item, Operation, Parameter, Media Type, and Security Requirement sections first; those are where Laravel-shaped APIs go wrong.
    • schemas/v3.1/schema.json — the JSON Schema for the document structure.
    • examples/v3.1/petstore.yaml — a complete, valid reference document to copy structure from.
    • registry/ — schema registry entries needed to resolve the $schema/jsonSchemaDialect references when validating offline.
  2. First real use case: validate the spec your app already generates. If you use Scramble, Scribe, or zircote/swagger-php, you have an openapi.json artifact — assert in Pest that it is structurally valid:

// tests/Feature/OpenApiDocumentTest.php
use Opis\JsonSchema\Validator;
use Opis\JsonSchema\Errors\ErrorFormatter;

it('emits a structurally valid OpenAPI 3.1 document', function () {
    $schema = json_decode(file_get_contents(resource_path('openapi/schemas/v3.1/schema.json')));
    $doc    = json_decode(file_get_contents(base_path('public/openapi.json')));

    $validator = new Validator();
    $validator->resolver()->registerFile(
        'https://spec.openapis.org/oas/3.1/schema/2022-10-07',
        resource_path('openapi/schemas/v3.1/schema.json')
    );

    $result = $validator->validate($doc, $schema);

    expect($result->isValid())->toBeTrue(
        json_encode((new ErrorFormatter())->format($result->error()), JSON_PRETTY_PRINT)
    );
});

That single test catches the majority of day-to-day breakage: malformed $refs, nullable left over from 3.0, non-x- vendor keys, bad status code keys, and invalid schema objects.

Implementation Patterns

Contract-first with the spec as the artifact, code as the derivative. Write or accept the openapi.yaml first, keep it in resources/openapi/, and generate what you need downstream: server-side validation middleware, TypeScript clients, Postman collections, static docs (Scalar, Redoc, Stoplight Elements). Laravel's role is to serve the file and enforce it, not to be the source of truth.

Request/response validation in a testing middleware. league/openapi-psr7-validator (or a thin wrapper around it) lets you assert that real HTTP traffic matches the spec. Wire it behind an env flag so it only runs in local/staging:

// app/Http/Middleware/ValidateAgainstOpenApi.php
public function handle($request, Closure $next)
{
    $psrRequest = (new Psr17Factory())->createRequestFromGlobals();
    $this->validator->validate($psrRequest);          // throws on violation
    $response = $next($request);
    $this->validator->validate($psrRequest, $this->toPsr($response));
    return $response;
}

Register conditionally in bootstrap/app.php ($middleware->appendIf(fn () => app()->environment('local'))). This is where the spec repo earns its keep: the validator's behaviour is defined entirely by the prose you're reading, and mismatches are almost always your spec being subtly wrong rather than the validator.

Lint with Spectral in CI alongside the schema check. The JSON Schema only proves the document is well-formed; it says nothing about API design quality. Point Spectral at the matching ruleset (oas3_1 vs oas3_0 — they differ) and fail the pipeline on error severity. Run both in the same CI step so a developer sees structural and stylistic failures together.

Breaking-change detection between branches. Dump the spec on main and on the PR branch, diff with oasdiff breaking, and post the result as a PR comment. This is the highest-leverage use of the repo for a team: the spec becomes the contract you can't silently break, and the diff is reviewable by non-PHP reviewers.

Split large specs by tag rather than by file. Most Laravel apps start with one openapi.yaml and hit a wall around 3–5k lines. Prefer splitting on $ref into paths/*.yaml and components/schemas/*.yaml with a bundler step (redocly bundle) that flattens to a single file before publishing — consumers and validators handle a single document far more reliably than a tree of relative refs.

Editor autocomplete from the vendored schema. Add to .vscode/settings.json so spec authors get inline validation without a language server:

{
  "yaml.schemas": {
    "./resources/openapi/schemas/v3.1/schema.json": ["resources/openapi/**/*.yaml"]
  }
}

Use examples/ as fixture templates. The petstore documents in examples/v3.0 and examples/v3.1 are maintained, valid, and show the 3.0→3.1 delta side by side. When you need to demonstrate a construct in a review or a test fixture, copy from there rather than from blog posts.

Version pinning in code, not just in git. Any tool that reads the spec (Scarlar/Redoc config, Spectral ruleset, validator) should declare its OpenAPI version explicitly; don't let it infer from whatever the newest release happens to be.

Gotchas and Tips

  • nullable: true is not a thing in 3.1. Use type: ["string", "null"]. Most PHP generators still emit nullable, and the 3.1 schema will happily accept the document while your consumers silently mis-handle the field. If your tooling is 3.0-only, target 3.0.3 deliberately rather than half-migrating.
  • Draft version mismatch is the #1 validator trap. 3.1 aligns with JSON Schema draft 2020-12; 3.0 uses a draft-04 subset. justinrainbow/json-schema does not support 2020-12 properly — use opis/json-schema v2 for 3.1, and pin the major.
  • Relative $refs break when you copy only schema.json. The 3.1 schema references the registry dialect. Either keep the directory layout intact, register the URI in the resolver (as in the test above), or run validation with network access disabled and a pre-registered resolver — otherwise you get confusing "unresolvable" errors that look like document bugs.
  • exclusiveMinimum changed type. Boolean in draft-04/3.0, number in 2020-12/3.1. A spec that validates under one dialect fails under the other with a message that rarely names the real cause.
  • main is unstable. Schema files get restructured between releases. Pin the tag in the submodule and in any CI download URLs.
  • Custom vendor keys must be x- prefixed. The schema enforces ^x-; a key like internalOwner: fails structural validation even though every human reader understands it.
  • YAML parsing is not YAML parsing. YAML 1.1 turns on/off/yes/no into booleans and may coerce date-like strings, which corrupts example values and enum members. Prefer JSON for anything generated, and use a 1.2 parser when authoring YAML — check that your Symfony\Yaml flags match what the consumer expects.
  • example (singular) vs examples (map). Both exist; in 3.1 under Media Type/Parameter, examples is a map of Example Objects. Mixing them produces documents that look right and behave inconsistently in mock servers.
  • The schema validates the document, not the design. No check that operationId is unique, that path params are declared, that 404 is documented, or that the security scheme is actually applied. That's Spectral's job — run both.
  • Path keys must start with / and templated params must be declared at either path-item or operation level. Undeclared {id} params are a documented error the schema may not catch depending on dialect strictness.
  • servers[].variables are not environment config. Don't try to model Laravel's env switching there; it's for documentation substitution only. Provide per-environment server lists in the published docs instead.
  • Debugging a validation failure: print the JSON Pointer from the validator error and paste it into the spec as a YAML anchor comment. Nine times out of ten the failing node is a $ref sibling — in 3.1 siblings of $ref are allowed, in 3.0 they are silently ignored, which is a common source of "my override does nothing" confusion.
  • Extension points. The spec itself has none — extension happens at the tooling layer (Spectral custom functions, custom JSON Schema format keywords registered in the resolver, generator plugins). If you find yourself wanting to extend the spec, you almost always want an x- vendor key plus a linter rule to enforce its shape.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core