steamcleaner / swagger-grails

Swagger Grails Plugin
MIT License
13 stars 5 forks source link

swagger-grails

Generate Swagger documentation for your Grails 5+ app.

Built With

Installation

Add this line to the repositories block in your build.gradle file:

maven { url "https://steamcleaner.jfrog.io/artifactory/grails-plugins" }

Add this line to the dependencies block in your build.gradle file:

implementation "org.grails.plugins:swagger-grails:0.5.0"

Usage

The following UrlMappings.groovy and AuthorController.groovy

class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?(.$format)?" {
            constraints {
                // apply constraints here
            }
        }

        "/authors"(resources: 'author')
    }
}
class AuthorController {
    def index() {/*...*/ }

    def save(AuthorCommand authorCommand) {/*...*/ }

    def show(String id) {/*...*/ }

    def delete(String id) {/*...*/ }

    def update(String id) {/*...*/ }

    def patch(String id) {/*...*/ }

    def custom(String name, int age) {/*...*/ }
}

class AuthorCommand implements Validateable {
    String name
}

will generate Swagger documentation like this :

This plugin will only generate the JSON representation of your endpoints. You'll need to implement your own swagger-ui to consume the JSON.

If your UrlMappings file includes the default "/$controller/$action?/$id?(.$format)?" mapping then the JSON will be accessible by hitting http://localhost:8080/swagger/api. This endpoint can be customized by adding " /custom/swagger/endpoint"(controller: "swagger", action: "api") to your UrlMappings file.

Also, any Swagger annotations that are manually added to an action in a controller, will be used when generating the Swagger documentation. So you could let the plugin do what it does by default and then enhance the actions with responses, authorizations, etc.

Configuration

The plugin also exposes the ability to customize the Swagger instance that is used.

The following resources.groovy will create the default swagger instance that the plugin will use. It also sets the security definition and security block. Together these two allow a header "apiKey" to be attached to all calls from the front end.

swagger(Swagger) {
    securityDefinitions = ["apiKey": new ApiKeyAuthDefinition("apiKey", In.HEADER)]
    security = [new SecurityRequirement().requirement("apiKey")]
}

Any of the fields on the Swagger object can be configured this way as well. For some more info on what can be configured the OpenAPI-Specification describes what the Swagger object can contain.

Running the plugin locally

The plugin source contains more examples of what types of configuration you can apply to controllers and actions :

Prerequisites
Running