Coder Social home page Coder Social logo

cakephp-swagger's Introduction

cakephp-swagger

Build Status StyleCI Status Coverage Status Total Downloads License

CakePHP 4.x plugin that adds auto-generated Swagger 2.0 documentation to your projects using swagger-php and swagger-ui.

Requirements

Installation

Install the plugin using composer:

composer require alt3/cakephp-swagger

Enabling

Enable the plugin in the bootstrap() method found in src/Application.php:

    public function bootstrap()
    {
        parent::bootstrap();
        $this->addPlugin('Alt3/Swagger');
    }

Also make sure that AssetMiddleware is loaded inside Application.php or all Swagger page assets will 404.

Installation check

After enabling the plugin, browsing to http://your.app/alt3/swagger should now produce the Swagger-UI interface:

Default UI index

Configuration

All configuration for this plugin is done through the /config/swagger.php configuration file. TLDR full example below.

<?php
use Cake\Core\Configure;

return [
    'Swagger' => [
        'ui' => [
            'title' => 'ALT3 Swagger',
            'validator' => true,
            'api_selector' => true,
            'route' => '/swagger/',
            'schemes' => ['http', 'https']
        ],
        'docs' => [
            'crawl' => Configure::read('debug'),
            'route' => '/swagger/docs/',
            'cors' => [
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Methods' => 'GET, POST',
                'Access-Control-Allow-Headers' => 'X-Requested-With'
            ]
        ],
        'library' => [
            'api' => [
                'include' => ROOT . DS . 'src',
                'exclude' => [
                    '/Editor/'
                ]
            ],
            'editor' => [
                'include' => [
                    ROOT . DS . 'src' . DS . 'Controller' . DS . 'AppController.php',
                    ROOT . DS . 'src' . DS . 'Controller' . DS . 'Editor',
                    ROOT . DS . 'src' . DS . 'Model'
                ]
            ]
        ]
    ]
];

UI section

Use the ui section to customize the following Swagger-UI options:

  • title: sets the Swagger-UI page title, defaults to cakephp-swagger
  • validator: show/hide the validator image, defaults to true
  • api_selector: show/hide the api selector form fields, defaults to true
  • route: expose the UI using a custom route, defaults to /alt3/swagger/
  • schemes: array used to specify third field used to generate the BASE URL (host is fetched realtime, basePath is also fetched realtime if not defined via annotations), defaults to null

Please note that the UI will auto-load the first document found in the library.

Docs section

Use the docs section to customize the following options:

  • crawl: enable to crawl-generate new documents instead of serving from filesystem, defaults to true
  • route: expose the documents using a custom route, defaults to /alt3/swagger/docs/
  • cors: specify CORS headers to send with the json responses, defaults to null

Library section

Use the library section to specify one or multiple swagger documents so:

  • swagger-php will know which files and folders to parse for annotations
  • swagger-php can produce the swagger json
  • this plugin can expose the json at http://your.app/alt3/swagger/docs/:id (so it can be used by the UI)

The following library example would result in:

  • swagger-php scanning all files and folders defined in include
  • swagger-php ignoring all files and folders defined in exclude
  • two endpoints serving json swagger documents:
    • http://your.app/alt3/swagger/docs/api
    • http://your.app/alt3/swagger/docs/editor
'library' => [
    'api' => [
        'include' => ROOT . DS . 'src',
        'exclude' => [
            '/Editor/'
        ]
    ],
    'editor' => [
        'include' => [
            ROOT . DS . 'src' . DS . 'Controller' . DS . 'AppController.php',
            ROOT . DS . 'src' . DS . 'Controller' . DS . 'Editor',
            ROOT . DS . 'src' . DS . 'Model'
        ]
    ]
]

It would also make http://your.app/alt3/swagger/docs produce a json list with links to all available documents similar to the example below.

{
    "success": true,
    "data": [
        {
            "document": "api",
            "link": "http://your.app/alt3/swagger/docs/api"
        },
        {
            "document": "editor",
            "link": "http://your.app/alt3/swagger/docs/editor"
        }
    ]
}

SwaggerShell

This plugin comes with a shell that should simplify deployment in production environments. Simply run the following command to create cakephp_swagger prefixed filesystem documents in tmp/cache for all entities found in your library.

bin/cake swagger makedocs <host>

The host argument (e.g. your.app.com) is required, should not include protocols and is used to set the host property inside your swagger documents.

Quickstart Annotation Example

Explaining swagger-php annotation voodoo is beyond this plugin but to give yourself a head start while creating your first library document you might want to copy/paste the following working example into any of your php files.

Note: the weird non-starred syntax ensures compatibility with the CakePHP Code Sniffer.

<?php
/**
    @SWG\Swagger(
        @SWG\Info(
            title="cakephp-swagger",
            description="Quickstart annotation example",
            termsOfService="http://swagger.io/terms/",
            version="1.0.0"
        )
    )

    @SWG\Get(
        path="/cocktails",
        summary="Retrieve a list of cocktails",
        tags={"cocktail"},
        consumes={"application/json"},
        produces={"application/json"},
        @SWG\Parameter(
            name="sort",
            description="Sort results by field",
            in="query",
            required=false,
            type="string",
            enum={"name", "description"}
        ),
        @SWG\Response(
            response="200",
            description="Successful operation",
            @SWG\Schema(
                type="object",
                ref="#/definitions/Cocktail"
            )
        ),
        @SWG\Response(
            response=429,
            description="Rate Limit Exceeded"
        )
    )

    @SWG\Definition(
        definition="Cocktail",
        required={"name", "description"},
        @SWG\Property(
            property="id",
            type="integer",
            description="CakePHP record id"
        ),
        @SWG\Property(
            property="name",
            type="string",
            description="CakePHP name field"
        ),
        @SWG\Property(
            property="description",
            type="string",
            description="Description of a most tasty cocktail"
        )
    )
*/

Which should result in:

UI Quickstart Example

Additional Reading

Contribute

Before submitting a PR make sure:

cakephp-swagger's People

Contributors

aceat64 avatar bravo-kernel avatar georgeconstantinou avatar mikedebruijn avatar mimorocks avatar pedro-stanaka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

cakephp-swagger's Issues

CakePHP 3.6 Support

Can we have a new major release compatible with CakePHP 3.6. I am up for the migration, are you accepting MRs?

Insecure UI validator image breaks green https status

Browser complains about insecure media when connecting to UI using HTTPS..

Update:
The warning is a known issue, to be fixed by the swagger team, caused by the Ui-generated validator button so... no issues in our index.ctp as explained by Chrome:

Mixed Content: The page at 'https://api.local/swagger' was loaded over HTTPS, but requested an insecure image 'http://online.swagger.io/validator/?url=https://api.local/swagger/docs/api'. This content should also be served over HTTPS.

See also:

Swagger UI "Try it out" button misses basePath

I have the following annotation :
/** @SWG\Swagger( schemes={"http", "https"}, host="API_HOST", basePath="/api", @SWG\Info( version="1.0.0", title="...", ) ) */

But when i press "Try it out", the request url does not include the basePath.
I've seen the lib/SwaggerTools file containing line 50 :
// set object properties required by UI to generate the BASE URL $swagger->host = $host; $swagger->basePath = '/' . Configure::read('App.base');

path parameters

I have a parameter defined as
@swg\Parameter(
name="id",
description="contact primary id",
in="path",
required=false,
type="integer",
)

On the UI it shows correctly as

Description Parameter Type Data Type
contact primary id path integer

When I click the try it now the try it now button the Value i entered doesnt get added to the path.

Any ideas?
Thanks

Index.ctp for Ui template references undefined variable

In cakephp-swagger/src/Template/Ui/index.ctp file, $userConfig should be $uiConfig. Currently the title field never gets reflected with what is being set in swagger.php file because $userConfig is not set from the controller, only $uiConfig is set.

Generate real documents instead of using cache

Replace the current (flakey) caching mechanism used to store the generated documents by actual filesystem documents/files. This would:

  • solve the problem of expired cache keys throwing (totally unpredictable) exceptions
  • help in debugging the documents

Alternative way of validation

Hey guys, thank you for a great plugin:)
I've been having some trouble working with the validator, I only get appropriate errors on the docs page, and the page has to be refreshed in order to check for errors which I find tiresome.

So to fix this I've created a small gulp script which watches for changes in my files. Upon a detected change, the script validates the swagger doc and generate a new doc that I save to another repository to which my clients are subscribed too.

I thought you might find it useful, so here it is:)

var gulp = require('gulp');
var swagger = require('gulp-swagger');
const shell = require('gulp-shell')

var api_path = './src/controller/api/**/*.php'
var definitions_path = './src/model/swagger/**/*.php';
var swagger_json_path = './tmp/cache/cakephp_swagger_api.json';

gulp.task('validate', function() {
    gulp.src(swagger_json_path)
        .pipe(swagger('athgene_internal_api.json'))
        .pipe(gulp.dest('PATH_TO_REPO'));
});

gulp.task('compile_swagger', shell.task([
    './bin/cake swagger makedocs localhost:8765'
]));

gulp.task('default', ['validate']);

// Rerun the task when a file changes
gulp.task('watch', function () {
    gulp.watch(api_path, ['compile_swagger']);
    gulp.watch(definitions_path, ['compile_swagger']);
    gulp.watch(swagger_json_path, ['validate']);
});

OpenApi 3 support

As far as I understand, cakephp-swagger uses php-swagger in version 2 which did not support OpenApi 3. Is it possible to use cakephp-swagger with php-swagger version 3? Composer doesn't allow me to install php-swagger version 3 due to the requirements of cakephp-swagger.

Generate UI icon links using HtmlHelper

Hardcoded icon links found here should be generated using HtmlHelper.

    <link rel="icon" type="image/png" href="http://api.local/images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="http://api.local/images/favicon-16x16.png" sizes="16x16" />

Add swagger-php generated basePath

DocsController should generate the three fields used by Swagger-UI to generate and show the Base Url:

        basePath="/v0",
        host="your.api.local",
        schemes={"http", "https"},

NEVER specify these fields in the source code annotations as this will break deploying your app to environments using no/different basePath.

Update:
Only schemes should be configurable, basePath and host can be fetched realtime.

More information:

CakePHP 4.3: Router::plugin() is deprecated, use the non-static method RouteBuilder::plugin() instead

I recently updated my project to CakePHP 4.3, and I get this message:

[Deprecated (16384)](javascript:void(0);): `Router::plugin()` is deprecated, use the non-static method `RouteBuilder::plugin()` instead.
/var/www/repo/public/vendor/alt3/cakephp-swagger/config/routes.php, line: 56
You can disable all deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED`. Adding `vendor/alt3/cakephp-swagger/config/routes.php` to `Error.ignoredDeprecationPaths` in your `config/app.php` config will mute deprecations from that file only. [CORE/src/Core/functions.php, line 321]

I think the fix is quite easy (I've done it in my project already), Router::plugin() just needs to be changed to $routes->plugin() in config/routes.php.

If needed, I can open a pull request for that.

cannot access swagger ui

2019-01-03 19:22:12 Error: [Cake\Routing\Exception\MissingControllerException] Controller class Alt3 could not be found.
Request URL: /alt3/swagger

i cannot figure out the problem, it runs fine on my local system but on our staging server there is this issue

Https loading assets [QUESTION]

Hello, I'm stuck with mixed content error.
I'm on cloud hosting running https, but swagger try to load assets in HTTP.

Here is my swagger configuration

`
use Cake\Core\Configure;
return [
'Swagger' => [
'ui' => [
'title' => 'PBE API Documentation',
'validator' => true,
'api_selector' => true,
'route' => 'api/swagger/',
'schemes' => ['https']
],
'docs' => [
'crawl' => Configure::read('debug'),
'route' => '/swagger/docs/',
'cors' => [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST',
'Access-Control-Allow-Headers' => 'X-Requested-With'
]
],
'library' => [
'api' => [
'include' => ROOT . DS . 'src' . DS . 'Controller' . DS . 'Api',
'exclude' => [
'/Editor/'
]
]
]
]
];

`

Locally it works but not in production.

I don't understand.

Thank you, for your time

Allow to modify API basePath via annotations

Hey,

First of all, thanks for the plugin!

Having the API basePath derived from Configure::read('App.base') is good, but if you have an application where your API endpoints are prefixed (e.g. /api) and this app also serves static content or crud as the webpages this might be an issue.
So, having an option to define API basePath via annotations might help. Basically, if basePath is defined via annotations we use it or App.base otherwise.

The fix is quite trivial but I can create a PR if needed.
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.