PHPackages                             php-openapi/openapi - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. php-openapi/openapi

ActiveLibrary[API Development](/categories/api)

php-openapi/openapi
===================

Read and write OpenAPI yaml/json files and make the content accessible in PHP objects.

2.1.0(3mo ago)4127.7k↓23.1%[1 PRs](https://github.com/openapi-php/php-openapi/pulls)4MITPHPPHP ^8.1 || ^8.2 || ^8.3 || ^8.4 || ^8.5CI passing

Since Jan 26Pushed 3mo ago4 watchersCompare

[ Source](https://github.com/openapi-php/php-openapi)[ Packagist](https://packagist.org/packages/php-openapi/openapi)[ Docs](https://github.com/openapi-php/php-openapi)[ RSS](/packages/php-openapi-openapi/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (11)Versions (12)Used By (4)

php-openapi
===========

[](#php-openapi)

Read and write [OpenAPI](https://www.openapis.org/) 3.x YAML and JSON files and make the content accessible in PHP objects.

It also provides a CLI tool for validating and converting OpenAPI 3.x Description files.

Supported OpenAPI versions:

- 3.0.x
- 3.1.x

[![Latest Stable Version](https://camo.githubusercontent.com/109f7d254f97525353b3b408e5491be5352aa520d341519aad4579242b28ca6d/687474703a2f2f706f7365722e707567782e6f72672f7068702d6f70656e6170692f6f70656e6170692f76)](https://packagist.org/packages/php-openapi/openapi)[![Total Downloads](https://camo.githubusercontent.com/17a516e95fdedfe42201358a5757a5288a458ec548f804cd3fc995d93800a4a1/687474703a2f2f706f7365722e707567782e6f72672f7068702d6f70656e6170692f6f70656e6170692f646f776e6c6f616473)](https://packagist.org/packages/php-openapi/openapi)[![Build Status](https://github.com/openapi-php/php-openapi/workflows/CI/badge.svg)](https://github.com/openapi-php/php-openapi/actions)

Install
-------

[](#install)

> composer require php-openapi/openapi

Used by
-------

[](#used-by)

This library provides a low level API for reading and writing OpenAPI files. It is used by higher level tools to do awesome work:

-
- Used by the original `cebe/php-openapi`
    - [cebe/yii2-openapi](https://github.com/cebe/yii2-openapi) Code Generator for REST API from OpenAPI 3 Descriptions, includes fake data generator.
    - [cebe/yii2-app-api](https://github.com/cebe/yii2-app-api) Yii framework application template for developing API-first applications.
    - [league/openapi-psr7-validator](https://github.com/thephpleague/openapi-psr7-validator) validates PSR-7 messages (HTTP request/response) against OpenAPI descriptions.
    - [dsuurlant/response2schema](https://github.com/dsuurlant/response2schema) a quick and easy tool for generating OpenAPI schemas based on example data.
- ... ([add yours](https://github.com/openapi-php/php-openapi/edit/main/README.md#L24))

Usage
-----

[](#usage)

### CLI Tool

[](#cli-tool)

```
$ vendor/bin/php-openapi help
PHP OpenAPI 3 tool
------------------
by Carsten Brandt

Usage:
  php-openapi  [] [input.yml|input.json] [output.yml|output.json]

  The following commands are available:

    validate   Validate the API Description in the specified input file against the OpenAPI v3.0 schema.
               Note: the validation is performed in two steps. The results are composed of
                (1) structural errors found while reading the API Description file, and
                (2) violations of the OpenAPI v3.0 schema.

               If no input file is specified input will be read from STDIN.
               The tool will try to auto-detect the content type of the input, but may fail
               to do so. You may specify --read-yaml or --read-json to force the file type.

               Exits with code 2 on validation errors, 1 on other errors and 0 on success.

    convert    Convert a JSON or YAML input file to JSON or YAML output file.

               If no input file is specified input will be read from STDIN.
               If no output file is specified output will be written to STDOUT.
               The tool will try to auto-detect the content type of the input and output file, but may fail
               to do so. You may specify --read-yaml or --read-json to force the input file type.
               and --write-yaml or --write-json to force the output file type.

               By default all references are resolved (replaced with the object referred to). You can control
               handling of references with the following arguments:

               --resolve-none      Do not resolve references.
               --resolve-external  Only resolve references that point to external files.
                                   This process is often referred to as "inlining".
               --resolve-all       Resolve all references (default).
                                   Recursive pointers will stay references.

    inline     Convert a JSON or YAML input file to JSON or YAML output file and
               resolve all external references. The output will be a single API Description file.
               This is a shortcut for calling convert --resolve-external.

    help       Shows this usage information.

  Options:

    --read-json   force reading input as JSON. Auto-detect if not specified.
    --read-yaml   force reading input as YAML. Auto-detect if not specified.
    --write-json  force writing output as JSON. Auto-detect if not specified.
    --write-yaml  force writing output as YAML. Auto-detect if not specified.
    -s, --silent  silent mode. Will hide all success/information messages and only print errors.

```

### Reading API Description Files

[](#reading-api-description-files)

Read OpenAPI Description from JSON file:

```
use openapiphp\openapi\Reader;

// realpath is needed for resolving references with relative Paths or URLs
$openapi = Reader::readFromJsonFile(realpath('openapi.json'));
```

Read OpenAPI Description from YAML:

```
use openapiphp\openapi\Reader;

// realpath is needed for resolving references with relative Paths or URLs
$openapi = Reader::readFromYamlFile(realpath('openapi.yaml'));
// you may also specify the URL to your API Description file
$openapi = Reader::readFromYamlFile('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.0.2/examples/v3.0/petstore-expanded.yaml');
```

Access API Description data:

```
echo $openapi->openapi; // openAPI version, e.g. 3.0.0
echo $openapi->info->title; // API title
foreach($openapi->paths as $path => $definition) {
    // iterate path definitions
}
```

Object properties are exactly like in the [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#openapi-specification). You may also access additional properties added by [specification extensions](https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#specificationExtensions).

### Writing API Description Files

[](#writing-api-description-files)

```
use openapiphp\openapi\spec\OpenApi;
use openapiphp\openapi\spec\PathItem;

// create base API Description
$openapi = new OpenApi([
    'openapi' => '3.0.2',
    'info' => [
        'title' => 'Test API',
        'version' => '1.0.0',
    ],
    'paths' => [],
]);
// manipulate description as needed
$openapi->paths['/test'] = new PathItem([
    'description' => 'something'
]);
// ...

$json = \openapiphp\openapi\Writer::writeToJson($openapi);
```

results in the following JSON data:

```
{
    "openapi": "3.0.0",
    "info": {
        "title": "Test API",
        "version": "1.0.0"
    },
    "paths": {
        "/test": {
            "description": "something"
        }
    }
}
```

### Writing API Description Files using prepared Objects

[](#writing-api-description-files-using-prepared-objects)

Since version 1.2.0, the above example can also be written like this (passing objects instead of arrays):

```
use openapiphp\openapi\spec\OpenApi;
use openapiphp\openapi\spec\PathItem;
use openapiphp\openapi\spec\Info;

// create base API Description
$openapi = new OpenApi([
    'openapi' => '3.0.2',
    'info' => new Info([
        'title' => 'Test API',
        'version' => '1.0.0',
    ]),
    'paths' => [
        '/test' => new PathItem([
            'description' => 'something'
        ]),
    ],
]);
$json = \openapiphp\openapi\Writer::writeToJson($openapi);
```

### Reading API Description Files and Resolving References

[](#reading-api-description-files-and-resolving-references)

In the above we have passed the raw JSON or YAML data to the Reader. In order to be able to resolve references to structures in external files, we must provide the full context.

```
use openapiphp\openapi\Reader;
use openapiphp\openapi\spec\OpenAPI;
use openapiphp\openapi\ReferenceContext;

// there are two different modes for resolving references:
// ALL: resolve all references, which will result in a large description with a lot of repetition
// but no references (except if there are recursive references, these will stop at some level)
$mode = ReferenceContext::RESOLVE_MODE_ALL;
// INLINE: only references to external files are resolved, references to places in the current file
// are still Reference objects.
$mode = ReferenceContext::RESOLVE_MODE_INLINE;

// an absolute URL or file path is needed to allow resolving external references
$openapi = Reader::readFromJsonFile('https://www.example.com/api/openapi.json', OpenAPI::class, $mode);
$openapi = Reader::readFromYamlFile('https://www.example.com/api/openapi.yaml', OpenAPI::class, $mode);
```

If data has been loaded in a different way you can manually resolve references like this by giving a context:

```
$openapi->resolveReferences(
    new \openapiphp\openapi\ReferenceContext($openapi, 'https://www.example.com/api/openapi.yaml')
);
```

### Validation

[](#validation)

The library provides simple validation operations, that check basic OpenAPI spec requirements. This is the same as "structural errors found while reading the API Description file" from the CLI tool. This validation does not include checking against the OpenAPI v3.0/v3.1 JSON schemas, this is only implemented in the CLI.

```
// return `true` in case no errors have been found, `false` in case of errors.
$specValid = $openapi->validate();
// after validation getErrors() can be used to retrieve the list of errors found.
$errors = $openapi->getErrors();

```

> **Note:** Validation is done on a very basic level and is not complete. So a failing validation will show some errors, but the list of errors given may not be complete. Also a passing validation does not necessarily indicate a completely valid spec.

Development
===========

[](#development)

You may use the docker environment for local development:

```
# Build once the container
docker build -t php-openapi .
# Run commands in the container
docker run -it -v `pwd`:/var/www -w /var/www php-openapi sh
```

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance82

Actively maintained with recent releases

Popularity36

Limited adoption so far

Community28

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 67.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~139 days

Recently: every ~192 days

Total

9

Last Release

92d ago

Major Versions

0.1.0 → 1.0.02023-01-26

1.0.3 → 2.02024-02-17

PHP version history (4 changes)0.1.0PHP &gt;=7.1.0

2.0PHP ^8.1 || ^8.2 || ^8.3

2.0.2PHP ^8.1 || ^8.2 || ^8.3 || ^8.4

2.1.0PHP ^8.1 || ^8.2 || ^8.3 || ^8.4 || ^8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/261a6249c6f605f3956a2fae40fbb813f6b2e1e6f2bf806180c851a965426e54?d=identicon)[cebe](/maintainers/cebe)

![](https://www.gravatar.com/avatar/f5cbc6024bba4a6e19ba1528504ff31452a1443a674f25d855aeef9f1e9f4ff7?d=identicon)[marcelthole](/maintainers/marcelthole)

---

Top Contributors

[![cebe](https://avatars.githubusercontent.com/u/189796?v=4)](https://github.com/cebe "cebe (222 commits)")[![marcelthole](https://avatars.githubusercontent.com/u/850125?v=4)](https://github.com/marcelthole "marcelthole (26 commits)")[![DEVizzent](https://avatars.githubusercontent.com/u/40741634?v=4)](https://github.com/DEVizzent "DEVizzent (14 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (11 commits)")[![simPod](https://avatars.githubusercontent.com/u/327717?v=4)](https://github.com/simPod "simPod (8 commits)")[![lezhnev74](https://avatars.githubusercontent.com/u/10206110?v=4)](https://github.com/lezhnev74 "lezhnev74 (6 commits)")[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (5 commits)")[![nadar](https://avatars.githubusercontent.com/u/3417221?v=4)](https://github.com/nadar "nadar (4 commits)")[![WyriHaximus](https://avatars.githubusercontent.com/u/147145?v=4)](https://github.com/WyriHaximus "WyriHaximus (3 commits)")[![SilverFire](https://avatars.githubusercontent.com/u/4499203?v=4)](https://github.com/SilverFire "SilverFire (3 commits)")[![canvural](https://avatars.githubusercontent.com/u/1574232?v=4)](https://github.com/canvural "canvural (2 commits)")[![il-masaru-yamagishi](https://avatars.githubusercontent.com/u/180239017?v=4)](https://github.com/il-masaru-yamagishi "il-masaru-yamagishi (2 commits)")[![izucken](https://avatars.githubusercontent.com/u/10879740?v=4)](https://github.com/izucken "izucken (2 commits)")[![karsa-mistmere](https://avatars.githubusercontent.com/u/17746067?v=4)](https://github.com/karsa-mistmere "karsa-mistmere (2 commits)")[![mfrischbutter](https://avatars.githubusercontent.com/u/33195197?v=4)](https://github.com/mfrischbutter "mfrischbutter (2 commits)")[![the-csaba](https://avatars.githubusercontent.com/u/45931795?v=4)](https://github.com/the-csaba "the-csaba (2 commits)")[![thejamescollins](https://avatars.githubusercontent.com/u/108233?v=4)](https://github.com/thejamescollins "thejamescollins (2 commits)")[![jongotlin](https://avatars.githubusercontent.com/u/165154?v=4)](https://github.com/jongotlin "jongotlin (1 commits)")[![scaytrase](https://avatars.githubusercontent.com/u/6578413?v=4)](https://github.com/scaytrase "scaytrase (1 commits)")[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (1 commits)")

---

Tags

openapi

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/php-openapi-openapi/health.svg)

```
[![Health](https://phpackages.com/badges/php-openapi-openapi/health.svg)](https://phpackages.com/packages/php-openapi-openapi)
```

###  Alternatives

[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k34.0M112](/packages/darkaonline-l5-swagger)[cebe/php-openapi

Read and write OpenAPI yaml/json files and make the content accessable in PHP objects.

49815.4M86](/packages/cebe-php-openapi)[darkaonline/swagger-lume

OpenApi or Swagger integration to Lumen

3372.3M3](/packages/darkaonline-swagger-lume)[devizzent/cebe-php-openapi

Read and write OpenAPI yaml/json files and make the content accessable in PHP objects.

379.0M49](/packages/devizzent-cebe-php-openapi)[harmbandstra/swagger-ui-bundle

Exposes swagger UI inside your Symfony project through a route (eg. /docs)

42867.3k](/packages/harmbandstra-swagger-ui-bundle)[jane-php/open-api-3

Generate a PHP Client API (PSR7/PSR18 compatible) given a OpenApi 3.x specification

201.4M87](/packages/jane-php-open-api-3)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
