Package creating swagger documentation.

2.7.0 2021-03-26 08:57 UTC

This package is auto-updated.

Last update: 2021-05-26 09:19:49 UTC


A PHP package to simplify the generation of Swagger 2.0 JSON documentation.

The specification for Swagger 2.0 can be found here.

Example Usage

Below is a basic example for setting up an API that has an endpoint for creating users. It should be pretty self explanatory if you are using an IDE with auto-complete. All that you need to know is that you need to create a \Programster\Swagger\Document object. Once you have managed to create it, you can just print it.


 * A script to generate the swagger JSON documentation.

require_once(__DIR__ . '/vendor/autoload.php');

// add a path/endpoint for users

$userReference = array();
$userReference['$ref'] = "#definitions/user";

$userProperties = array(
    Programster\Swagger\DefinitionProperty::createBasic("id", \Programster\Swagger\Type::createInt(), "The ID of the user."),
    Programster\Swagger\DefinitionProperty::createBasic("first_name", \Programster\Swagger\Type::createString(), "The first name of the user."),
    Programster\Swagger\DefinitionProperty::createBasic("last_name", \Programster\Swagger\Type::createString(), "The last name of the user."),
    Programster\Swagger\DefinitionProperty::createArray("friends", \Programster\Swagger\Type::createInt(), "The list of user IDs that are friends with this user."),

$userDefinition = new Programster\Swagger\Definition("User", "A user object", ...$userProperties);
$successResponse = new \Programster\Swagger\Response(200, "User successfully created.", $userDefinition);

$firstNameParameter = new \Programster\Swagger\Parameter(
    "The first name of the user", 

$lastNameParameter = new \Programster\Swagger\Parameter(
    "The last name of the user", 

$createUserParameters = new Programster\Swagger\ParameterCollection($firstNameParameter, $lastNameParameter);

// add a "POST" action to the users path for creating a user
$createUserAction = new Programster\Swagger\PathAction(
    "Add a user to the system", 
    "Add a user to the system",
    new \Programster\Swagger\ResponseCollection($successResponse)

$usersPath = new \Programster\Swagger\Path("/users", $createUserAction);
$paths = new Programster\Swagger\PathCollection($usersPath);

$definitions = new Programster\Swagger\DefinitionCollection($userDefinition);

$document = new \Programster\Swagger\Document(
    "My RESTful API", 
    "A service that does something useful.",

file_put_contents(__DIR__ . '/swagger.json', $document);
print "Swagger documentation updated. Don't forget to commit." . PHP_EOL;

If you were to run that script, you would generate a swagger.json output file which you can link to from a swagger-UI page (as long as you enable CORS), or you can paste it directly into an online swagger editor.