We have a Swagger file for our API, but in our API documentation, we want to show valid responses for each endpoint. I coded up this little recursive function in PHP which takes our Swagger file and spits out a valid response.

I use it as follows, for each individual endpoint:

// $swagger is the entire swagger file
$swagger = file_get_contents('/path-to-swagger.json');

For the below code within our PHP template, $endpoint can be assumed to be a single endpoint with method (e.g. a single POST request to a URI) such that json_decode() was used to convert it from the Swagger file to a PHP array.

<pre><?= json_encode(swagger_to_model(
    $swagger['definitions'][str_replace('#/definitions/','', $endpoint['responses']['200']['schema']['$ref'])]['properties'],
    $swagger['definitions'],
    0,
    $definitions
), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) ?></pre>
520 Views

function swagger_to_model($response, $swagger, $depth = 0, &$definitions = array())
{                
    if (is_scalar($response))
    {
        return $response;
    }
    else if (isset($response['format']))
    {
        return $response['format'];
    }
    else if (isset($response['type']))
    {
        if ($response['type'] == 'array')
        {
            return array(swagger_to_model($response['items'], $swagger, $depth, $definitions));
        }
        else if ($response['type'] == 'object')
        {
            if (isset($response['properties']))
            {
                return swagger_to_model($response['properties'], $swagger, $depth, $definitions);
            }
            else 
            {
                return swagger_to_model($response['additionalProperties'], $swagger, $depth, $definitions);
            }
        }
        else
        {
            return $response['type'];
        }
    }
    else if (isset($response['$ref']))
    {        
        $definition = str_replace('#/definitions/', '', $response['$ref']);
        
        // Add to the list of definitions being used here
        $definitions[] = $definition;        
                
        if ($depth > 1)
        {
            return array(
                'id' => 'int32'
            );
        }
        
        return swagger_to_model($swagger[$definition]['properties'], $swagger, ++$depth, $definitions);
    }    
    else
    {
        $output = array();
                
        foreach ($response AS $key => $value)
        {
            $output[$key] = swagger_to_model($value, $swagger, $depth, $definitions);
        }
        
        return $output;
    }
}
About the Author

I'm a super-geeky programmer with a passion for Internet marketing. :)