Convert Figma logo to code with AI

zircote logoswagger-php

A php swagger annotation and parsing library

5,056
931
5,056
43

Top Related Projects

The OpenAPI Specification Repository

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API

23,450

📘 OpenAPI/Swagger-generated API Reference Documentation

4,272

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

API Blueprint

36,008

Beautiful static documentation for your API

Quick Overview

Swagger-php is a PHP library that allows developers to generate OpenAPI (formerly Swagger) documentation for their APIs directly from PHP source code annotations. It simplifies the process of creating and maintaining API documentation by integrating it with the codebase.

Pros

  • Seamless integration with PHP code, allowing documentation to be written alongside the implementation
  • Automatic generation of OpenAPI/Swagger specifications from PHP annotations
  • Supports OpenAPI 3.0 and Swagger 2.0 specifications
  • Extensive customization options for fine-tuning the generated documentation

Cons

  • Learning curve for developers unfamiliar with OpenAPI/Swagger annotations
  • May require additional setup and configuration for complex API structures
  • Generated documentation might need manual adjustments for edge cases or complex scenarios
  • Potential for documentation to become outdated if annotations are not properly maintained

Code Examples

  1. Basic API endpoint documentation:
/**
 * @OA\Get(
 *     path="/users/{id}",
 *     summary="Get user information",
 *     @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
 *     @OA\Response(response="200", description="Successful operation")
 * )
 */
public function getUser($id) {
    // Implementation
}
  1. Defining a schema for a model:
/**
 * @OA\Schema(
 *     schema="User",
 *     @OA\Property(property="id", type="integer"),
 *     @OA\Property(property="name", type="string"),
 *     @OA\Property(property="email", type="string", format="email")
 * )
 */
class User {
    // Class implementation
}
  1. Documenting request body:
/**
 * @OA\Post(
 *     path="/users",
 *     summary="Create a new user",
 *     @OA\RequestBody(
 *         @OA\JsonContent(ref="#/components/schemas/User")
 *     ),
 *     @OA\Response(response="201", description="User created")
 * )
 */
public function createUser(Request $request) {
    // Implementation
}

Getting Started

  1. Install swagger-php via Composer:

    composer require zircote/swagger-php
    
  2. Add annotations to your PHP code (see examples above).

  3. Generate the OpenAPI documentation:

    <?php
    require("vendor/autoload.php");
    $openapi = \OpenApi\Generator::scan(['path/to/your/api']);
    header('Content-Type: application/x-yaml');
    echo $openapi->toYaml();
    
  4. Use the generated YAML or JSON with Swagger UI or other OpenAPI tools to display your API documentation.

Competitor Comparisons

The OpenAPI Specification Repository

Pros of OpenAPI-Specification

  • Language-agnostic specification, allowing for broader adoption across different programming languages and frameworks
  • Serves as the official standard for OpenAPI/Swagger, ensuring consistency and compatibility
  • Provides a comprehensive set of guidelines for API description, including security schemes, request/response formats, and more

Cons of OpenAPI-Specification

  • Requires manual writing of API specifications, which can be time-consuming and error-prone
  • Lacks built-in code generation capabilities, necessitating additional tools for implementation

Code Comparison

OpenAPI-Specification (YAML):

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
paths:
  /users:
    get:
      summary: List users

swagger-php (PHP):

/**
 * @OA\Info(title="Sample API", version="1.0.0")
 */
class ApiController
{
    /**
     * @OA\Get(path="/users", summary="List users")
     */
    public function listUsers() {}
}

Summary

OpenAPI-Specification provides a language-agnostic standard for API documentation, offering comprehensive guidelines and broad compatibility. However, it requires manual specification writing and lacks built-in code generation. swagger-php, on the other hand, allows for inline PHP annotations to generate OpenAPI specifications, which can be more convenient for PHP developers but may limit its use in other languages.

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API

Pros of swagger-core

  • More comprehensive support for Java ecosystem
  • Wider range of annotations and customization options
  • Better integration with Spring Framework

Cons of swagger-core

  • Steeper learning curve for non-Java developers
  • Less flexibility for PHP-specific features
  • Requires more configuration for non-Java projects

Code Comparison

swagger-core (Java):

@Path("/users")
@Api(value = "/users", description = "User operations")
public class UserResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get all users", response = User.class, responseContainer = "List")
    public Response getUsers() {
        // Implementation
    }
}

swagger-php (PHP):

/**
 * @OA\Get(
 *     path="/users",
 *     summary="Get all users",
 *     @OA\Response(
 *         response=200,
 *         description="Successful operation",
 *         @OA\JsonContent(type="array", @OA\Items(ref="#/components/schemas/User"))
 *     )
 * )
 */
public function getUsers() {
    // Implementation
}

Both libraries provide annotations for defining API endpoints and their properties. swagger-core offers more Java-specific annotations, while swagger-php uses PHP DocBlocks for OpenAPI definitions. swagger-core is better suited for Java projects, especially those using Spring, while swagger-php is more appropriate for PHP applications, offering a simpler syntax for PHP developers.

23,450

📘 OpenAPI/Swagger-generated API Reference Documentation

Pros of Redoc

  • Offers a more visually appealing and interactive documentation interface
  • Supports themes and customization options for better branding
  • Provides a responsive design for mobile and desktop viewing

Cons of Redoc

  • Focuses primarily on documentation rendering, not OpenAPI/Swagger generation
  • May require additional setup and configuration for complex API structures
  • Limited to OpenAPI/Swagger format, while swagger-php supports PHP annotations

Code Comparison

Redoc (HTML embedding):

<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="https://api.example.com/openapi.json"></redoc>

swagger-php (PHP annotation):

/**
 * @OA\Info(
 *     title="My API",
 *     version="1.0.0"
 * )
 */
class ApiController {}

Summary

Redoc excels in rendering beautiful, interactive API documentation from OpenAPI/Swagger specifications. It's ideal for presenting APIs to end-users and developers. swagger-php, on the other hand, focuses on generating OpenAPI/Swagger specifications from PHP annotations, making it more suitable for PHP developers working on API development. While Redoc provides a polished front-end experience, swagger-php offers a convenient way to maintain API documentation alongside PHP code.

4,272

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Pros of Prism

  • Language-agnostic API mocking and validation tool
  • Supports multiple API description formats (OpenAPI, Swagger, RAML)
  • Provides a CLI for easy integration into development workflows

Cons of Prism

  • Requires separate installation and setup
  • May have a steeper learning curve for PHP-specific projects
  • Less tightly integrated with PHP codebases

Code Comparison

Prism (CLI usage):

prism mock -p 4010 ./api-description.yaml

swagger-php (PHP annotation):

/**
 * @OA\Info(title="My API", version="1.0.0")
 */
class ApiController
{
    // ...
}

Key Differences

  • Prism is a standalone tool, while swagger-php is a PHP library
  • Prism focuses on mocking and validation, swagger-php on generating OpenAPI specifications
  • Prism works with multiple API description formats, swagger-php is specific to OpenAPI/Swagger
  • swagger-php integrates directly into PHP code using annotations, Prism operates on separate API description files

Use Cases

  • Choose Prism for language-agnostic API mocking and testing
  • Use swagger-php for generating OpenAPI specifications from PHP code
  • Consider using both tools in combination for a comprehensive API development workflow in PHP projects

API Blueprint

Pros of API Blueprint

  • Uses a simple, human-readable Markdown-based syntax
  • Supports a wider range of API description formats beyond just REST
  • Offers a more flexible and extensible documentation structure

Cons of API Blueprint

  • Less widespread adoption compared to Swagger/OpenAPI
  • Fewer tools and integrations available in the ecosystem
  • May require additional parsing and conversion for some use cases

Code Comparison

API Blueprint example:

# GET /users/{id}
+ Parameters
    + id: 1 (number, required) - User ID
+ Response 200 (application/json)
    + Attributes
        + name: John Doe (string)
        + email: john@example.com (string)

Swagger-PHP example:

/**
 * @OA\Get(
 *     path="/users/{id}",
 *     @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
 *     @OA\Response(
 *         response=200,
 *         description="Successful response",
 *         @OA\JsonContent(
 *             @OA\Property(property="name", type="string", example="John Doe"),
 *             @OA\Property(property="email", type="string", example="john@example.com")
 *         )
 *     )
 * )
 */

Both API Blueprint and Swagger-PHP offer ways to document APIs, but they differ in syntax and approach. API Blueprint uses a more readable Markdown format, while Swagger-PHP relies on PHP annotations. The choice between them depends on your specific needs, existing tech stack, and preferred documentation style.

36,008

Beautiful static documentation for your API

Pros of Slate

  • Generates beautiful, responsive API documentation
  • Supports multiple languages and easy customization
  • Provides a clean, single-page layout for better user experience

Cons of Slate

  • Requires manual writing of documentation in Markdown
  • Less integration with existing code compared to Swagger-PHP
  • May require more setup and maintenance for complex APIs

Code Comparison

Slate (Markdown):

# Introduction

Welcome to the Kittn API! You can use our API to access Kittn API endpoints, which can get information on various cats, kittens, and breeds in our database.

## Authentication

> To authorize, use this code:

```ruby
require 'kittn'

api = Kittn::APIClient.authorize!('meowmeowmeow')

Swagger-PHP (PHP):

```php
/**
 * @OA\Info(
 *     title="Kittn API",
 *     version="1.0.0",
 *     description="API for accessing information on cats, kittens, and breeds"
 * )
 */

/**
 * @OA\SecurityScheme(
 *     type="apiKey",
 *     in="header",
 *     securityScheme="api_key",
 *     name="Authorization"
 * )
 */

Both Slate and Swagger-PHP offer unique approaches to API documentation. Slate focuses on creating visually appealing, customizable documentation, while Swagger-PHP integrates directly with PHP code for automated OpenAPI specification generation. The choice between them depends on specific project requirements, team preferences, and the desired balance between manual control and automation in documentation creation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build Status Total Downloads License

swagger-php

Generate interactive OpenAPI documentation for your RESTful API using doctrine annotations (optional as of version 4.8; if required the doctrine/annotations library must be installed in addition to swagger.php). or PHP attributes.

For a full list of supported annotations, please have look at the OpenApi\Annotations namespace or the documentation website.

Features

  • Compatible with the OpenAPI 3.0 and 3.1 specification.
  • Extracts information from code & existing phpdoc annotations.
  • Command-line interface available.
  • Documentation site with a getting started guide.
  • Exceptional error reporting (with hints, context)
  • As of PHP 8.1 all annotations are also available as PHP attributes

OpenAPI version support

swagger-php allows to generate specs either for OpenAPI 3.0.0 or OpenAPI 3.1.0. By default the spec will be in version 3.0.0. The command line option --version may be used to change this to 3.1.0.

Programmatically, the method Generator::setVersion() can be used to change the version.

Requirements

swagger-php requires at least PHP 7.2 for annotations and PHP 8.1 for using attributes.

Installation (with Composer)

composer require zircote/swagger-php

For cli usage from anywhere install swagger-php globally and make sure to place the ~/.composer/vendor/bin directory in your PATH so the openapi executable can be located by your system.

composer global require zircote/swagger-php

doctrine/annotations

As of version 4.8 the doctrine annotations library is optional and no longer installed by default.

To use PHPDoc annotations this needs to be installed on top of swagger-php:

composer require doctrine/annotations

If your code uses PHPDoc annotations you will need to install this as well:

composer require doctrine/annotations

Usage

Add annotations to your php files.

/**
 * @OA\Info(title="My First API", version="0.1")
 */

/**
 * @OA\Get(
 *     path="/api/resource.json",
 *     @OA\Response(response="200", description="An example resource")
 * )
 */

Visit the Documentation website for the Getting started guide or look at the Examples directory for more examples.

Usage from php

Generate always-up-to-date documentation.

<?php
require("vendor/autoload.php");
$openapi = \OpenApi\Generator::scan(['/path/to/project']);
header('Content-Type: application/x-yaml');
echo $openapi->toYaml();

Documentation of how to use the Generator class can be found in the Generator reference.

Usage from the Command Line Interface

The openapi command line interface can be used to generate the documentation to a static yaml/json file.

./vendor/bin/openapi --help

Starting with version 4 the default analyser used on the command line is the new ReflectionAnalyser.

Using the --legacy flag (-l) the legacy TokenAnalyser can still be used.

Usage from the Deserializer

Generate the OpenApi annotation object from a json string, which makes it easier to manipulate objects programmatically.

<?php

use OpenApi\Serializer;

$serializer = new Serializer();
$openapi = $serializer->deserialize($jsonString, 'OpenApi\Annotations\OpenApi');
echo $openapi->toJson();

Contributing

More on OpenApi & Swagger