Getting started with Laravel and Swagger Documentation

Swagger UI

So far we have our swagger documentation script working with it’s respective output. Now we need to add the user interface that will allow us to interact and test our endpoints.

The swagger.sh script generates a subfolder inside the public folder with a file called swagger.json which contains information for the UI about the endpoints and required data to test against.

/app
/public
|__ /swagger

Installation

In our swagger.sh script you may have noticed we specified which folder we wanted our swagger to output in.

User Interface

To add an interface go to https://github.com/swagger-api/swagger-ui and download the entire folder. Place it inside the swagger folder.

Script customization

Now that we have the user interface files set, we need to edit the file paths for swagger to work correctly.

Our index.html needs to be updated for our localhost server, you can copy and paste directly from here:

Swagger Annotations

Annotations are the format of writing swagger documentation so they can be generated into swagger.json and thus being testable.

Typically, annotations should be placed in your controllers that directly handle endpoints and validation (app/Http/Controllers).

Let’s start by learning what the most important annotation blocks do.

SWGGet() refers to what kind of HTTP method we’ll use, in this case, we’re fetching data (GET).

path, the route of our endpoint “/create”

SWGParameter() we have two parameters needed for our route — firstname and lastname

query, the parameter will be passed through a query string

SWGResponse() which kind of response and code will we return if the data is correct or incorrect.

Put the following Swagger annotations above your create() function and run ./swagger.sh one final time.

/**
*
@SWGGet(
* path="/create",
* description="Return a user's first and last name",
*
@SWGParameter(
* name="firstname",
* in="query",
* type="string",
* description="Your first name",
* required=true,
* ),
*
@SWGParameter(
* name="lastname",
* in="query",
* type="string",
* description="Your last name",
* required=true,
* ),
*
@SWGResponse(
* response=200,
* description="OK",
* ),
*
@SWGResponse(
* response=422,
* description="Missing Data"
* )
* )
*/

Tada!

You should be able to access the final result here.

End result of generating Swagger docs and Swagger UI Integration

By clicking on our route endpoint, we can input the firstname and lastname and execute the GET request

As with most tutorials, there is a lot to Swagger and documentation in general. I recommend you visit the package on Github to get a better understanding on how everything works and the syntax involved in more complex requests.

Thanks for reading!

View the original story at http://garrettvorce.com/laravel-and-swagger-documentation/

read original article here