Creating Golang API documentation using Swaggerui

Source: Internet
Author: User
Tags install go redoc
This is a creation in Article, where the information may have evolved or changed. Providing a document for your API is more useful than you might think, even if you don't expose your API, providing a document for your front-end or mobile team will be easier than you can offer/fragment or use Postman/insomnia (Advanced version with Sync). With Swaggerui, you can automatically get well-designed documentation for all your APIs. When I switched to go, I had some problems configuring it due to the lack of documentation/tutorials, so I decided to write one. [Goswagger] (https://raw.githubusercontent.com/studygolang/gctt-images/master/swagger-golang/swagger-golang1.jpg) sample program: [link] (Https://github.com/ribice/golang-swaggerui-example) About two years ago, when I was in the background of developing a RESTful enterprise app, I first knew [Swaggerui] (https:// swagger.io/swagger-ui/). Swaggerui's creator Smartbear described his product as:> "Swagger UI allows anyone, whether your development team or end user, to visualize and interact with API resources without any implementation logic. It (API documentation) is automatically generated through the Swagger definition, and visual documentation makes the backend implementation and client consumption easier. "In short, by providing Swagger (OpenAPI) definitions, you get an interface that interacts with the API without having to worry about the programming language itself." You can see Swagger (OpenAPI) as the WSDL for REST. As a reference, Swagger Codegen can generate both client and server code from this definition in dozens of programming languages. Back then, I was using Java and Springboot and felt Swagger easy to use. You only need to create the bean once, add one or two annotations to the endpoint, and add a title and an item description. In addition, I'm used to redirecting all requests from "/" to "/swagger-ui" to automatically jump to Swaggerui when I open ' host:port '. The Swaggerui is still available on the same port when the application is running. (For example, your application runs in ' [Host]:[port] ', Swaggerui will be accessed on ' [Host]:[port]/swagger-ui '). Soon after 1.5, I want to implement Swaggerui in our Go project. The problem is--it feels too complicated. When I search the Web, I see more than just me, and many other users are having the same trouble. I stumbled across the Go-swagger project. Their [GitHub Readme] (Https://github.com/go-swagger/go-swagger) is talking about swagger, not swaggerui. You have to have a client, server, middleware and some other stuff before you can consider Swaggerui. In short, the Swagger server/client is used to generate (back-end) code from the Swagger definition (Swagger.json). The build server allows you to provide APIs from the specification while generating clients for those API consumer. Think of it as a code generation tool. I think it's useful, but that's not what I want. With the help of the community (to [Casualjim] (Https://github.com/casualjim) and some surveys, I succeeded in generating API documentation for our project that did not have much boilerplate code. In addition, I have prepared an example that implements the Go-swagger annotation to generate a valid swagger document, which can be found [here] (https://github.com/ribice/golang-swaggerui-example). # # Install Go-swagger before you start, you need to install Go swagger on your local machine. This is not a mandatory step, but will make it easier to work with swagger. Installing it allows you to test your comments locally, otherwise you can only rely on your CI tool. The simplest way to install it is by running Homebrew/linuxbrew: ' consolebrew tap go-swagger/go-swaggerbrew install Go-swagger ' and also, you can get from [here] ( Https://github.com/ribice/golang-swaggerui-example) Get the latest binary files. # # Swagger:meta [[Docs]] (https://goswagger.io/generate/spec/meta.html)! [Swagger-meta] (Https://raw.gitHubusercontent.com/studygolang/gctt-images/master/swagger-golang/swagger-golang2.jpg) This is the first comment that you should add to the project. It is used to describe your project name, description, contact email, website, license and so on. If your API is only available on HTTP or HTTPS and only generates JSON, you should add it here-allowing you to remove the comment from each route. Security is also added to the Swagger:meta, and an authorization button is added to the Swaggerui. To implement JWT, I use the secure type hosting to name and define it as: "' go//security://-bearer////securitydefinitions://bearer://type:apikey//Name: authorization//in:header//"# # Swagger:route [[Docs]] (https://goswagger.io/generate/spec/route.html) There are two ways to annotate your route, Swagger:operation and Swagger:route. Two. Both look very similar, so what are the main differences? Consider Swagger:route as a short comment for the simple API, which is suitable for APIs that do not have input parameters (path/query parameters). Examples of those (with parameters) are/repos/{owner},/user/{id} or/users/search?name=ribice If you have one type, then you have to use swagger:operation, in addition, such as/ APIs such as user or/version can be annotated with Swagger:route. The **swagger:route** comment contains the following: ' go//swagger:route Post/repo repos users createreporeq//creates a new repository for the CU rrently authenticated user.//If repository name is "exists", error conflict (409) would be returned.//responses://200:r EpoResp//400:badreq//409:conflict//500:internal ' 1. **swagger:route**-NOTE 2. **post**-HTTP Method 3. /**repo**-Match path, endpoint 4. **repos**-the Space partition label where the route is located, for example, "Repos users" 5. **createreporeq**-Request for this endpoint (explained in detail later) 6. **creates a new repository ... * *-summary (title). For Swager:route comments, the title is preceded by the first period (.). If there is no period, there will be no title and the text will be used for the description. 7. **if Repository Name exists ... * *-description. For Swager:route type annotations, the description is followed by the first period (.). 8. **responses**:-Response of this endpoint 9. **200:reporesp**-A (successful) response to HTTP status 200, containing REPORESP (model annotated with Swagger:response) 10. **400:badreq, 409:conflict, 500:internal**-error response for this endpoint (error request, conflict and internal error, defined under Cmd/api/swagger/model.go) so note that your endpoint will produce the following:! [Swagger-route-ui] (https://raw.githubusercontent.com/studygolang/gctt-images/master/swagger-golang/swagger-golang3.jpg) Please remember that You may also want to use additional annotations, depending on your API. Since I've defined my project to use only single mode (HTTPS) and all my APIs use HTTPS, I don't need to annotate the scenario separately. If you use multiple modes for the endpoint, you need the following comment: "' go//schemes:http, HTTPS, WS, WSS ' also applies to consumer/producer media types. All of my APIs only consume/generate Application/json. If your API is consuming/generating other types, you will need to annotate them with that media type. For example: "' go//consumes://-application/json//-application/x-protobuf////produces://-application/json//-application/x-protobuf ' security: ' go//security://api_key://oauth:read, write//basicauth://type:basic//token://type:apikey//name:token//In:quer y//accesstoken://type:apikey//name:access_token//in:query "' On the other hand, swagger:operation is used for more complex endpoints. The sections under three dashes (-) are parsed into YAML, allowing for more complex annotations. Make sure that your indentation is consistent and correct, otherwise it will not resolve correctly. # # Swagger:operation [docs] (https://goswagger.io/generate/spec/operation.html) using swagger:operation allows you to use all [ OPENAPI specification] (https://swagger.io/specification/), you can describe your complex endpoints. If you are interested in the details, you can read the specification document. Simply put-swagger:operation contains the following: "go//swagger:operation get/repo/{author} repos repolist//---//summary:list the Repo Sitories owned by the given author.//description:if author length was between 6 and 8, Error not Found (404) would be Retu rned.//parameters://-name:author//in:path//description:username of author//type:string//required:true//respon ses://"$"://"$ref": "#/responses/reposresp"//"4"://" $ref ":" #/responses/notfound "" 1. **swagger:operation**-NOTE 2. **get**-HTTP Method 3. /**repo/{author}**-Match path, endpoint 4. **repos**-the Space partition label where the route is located, for example, "Repos users" 5. **repolist**-A request for this endpoint. This does not exist (not defined), but the parameters are mandatory, so you can replace repolist (noreq,emptyreq, etc.) with anything else 6. ----This section below is the Swagger specification for YAML format. Make sure that your indentation is consistent and correct, otherwise it will not resolve correctly. Note that if you define a label, summary, description or action tag in Yaml, the summary, description, tag, or action tag in the general swagger syntax above will be overwritten. 7. **summary**:-Title 8. **description**:-Description 9. **parameters**:-url parameter (in this case {author}). The string format, mandatory (swagger does not let you call the endpoint without entering), is located in the path (/{author}). Another option is to define your route after the request (? Name= ") is embedded in the parameter, and you need to define your request and response. From the example, you can see that I created a new package named Swagger. This is not mandatory, it puts all boilerplate code in a package called swagger. But the downside is that you must export all of your HTTP requests and responses. If you create a separate Swagger package, be sure to import it into your master/server file (you can do this by adding an underscore before importing): "Go_" github.com/ribice/golang-swaggerui-example/ Cmd/swagger "" ' # # Swagger:parameters [[Docs]] (https://goswagger.io/generate/spec/params.html) Depending on your application model, your HTTP Requests may be different (simple, complex, encapsulation, etc.). To generate the Swagger specification, you need to create a structure for each different request, even a simple request that contains only numbers (for example, IDS) or strings (names). Once you have such a structure (for example a structure that contains a string and a Boolean value), it is defined in your swagger package as follows: '"go//Request containing string//swagger:parameters createreporeqtype swaggercreatereporeq struct {//IN:BODYAPI. Createreporeq} '-The 1th line contains a comment that is visible on Swaggerui-the 2nd line contains the Swagger:parameters comment and the requested name (OperationID). This name is used as the last parameter of the routing comment to define the request. -line 4th contains the position of this parameter (in:body,in:query, etc.)-line 5th is the actual inline structure. As mentioned earlier, you do not need a separate swagger annotation package (you can put the swagger:parameters annotation in the API. Createreporeq), but once you start creating response comments and validations, then a separate package will be clearer in swagger related annotations. [Swagger-parameters] (https://raw.githubusercontent.com/studygolang/gctt-images/master/swagger-golang/swagger-golang4.jpg) If you have a big request, For example, create or update, you should create a new type of variable instead of an inline structure. For example (note the difference in line fifth): "' go//Request containing string//swagger:parameters createreporeqtype swaggercreatereporeq struct {// In:bodybody API. Createreporeq} "This will produce the following Swaggerui request:! [Swagger-patameters-ui] (https://raw.githubusercontent.com/studygolang/gctt-images/master/swagger-golang/swagger-golang5.jpg) Swagger has a number of validation comments available to swagger:parameters and Swagger:response, which are described in detail and used in the documentation next to the comment header. # # Swagger:response [[Docs]] (https://goswagger.io/generate/spec/response.html) Response comments are very similar to parameter annotations. The main difference is that you often wrap responses into more complex structures, so you have to take this into account in swagger. In my example, my success response is as follows: "json{" code ": $,//code containing HTTP status code" data ": {}//Data containing actual response Da TA} "Although the error response is a little different:" ' json{"code": ",//code containing HTTP status code" message ":" "//String containing error message} "To use a regular response, like the above error response, I usually create model.go (or swagger.go) inside the swagger package and define them inside. In the example, the following response is used for an OK response (no data returned): "' go//Success response//swagger:response oktype swaggscsresp struct {//in:bodybody struct {//HTTP status Code 200-okcode int ' JSON: ' Code '}} "For error responses, most of them are similar to each other except for names (and HTTP code comments in the case of examples). Nonetheless, you should still define each of the wrong situations so that you can respond as possible to your endpoint: "' go//error forbidden//swagger:response forbiddentype Swaggerrforbidden struct {//in:bodybody struct {//HTTP status Code 403-forbiddencode int ' JSON: ' Code '//Detailed error messagemessage s Tring ' JSON: ' Message ' '} ' data contains model. Sample response for Repository: ' go//HTTP status code Repository in data//SWAGGER:RESPONSE Reporesptype swaggreporesp struct {//in:bodybody struct {//HTTP status Code 200/201code int ' JSON: "Code" '//Reposito Ry Modeldata model. Repository ' JSON: ' Data ' contains model. Sample response for the Repository slice: ' go//HTTP status code $ and an array of Repository models in data//swagger:response Reposresptype SWAGGREPOSRESP struct {//in:bodybody struct {//HTTP status code 200-status okcode int ' JSON: "Code" '//Array of Reposi Tory Modelsdata []model. Repository ' JSON: ' Data ' '} ' in short, this will be enough to generate your API documentation. You should also add validation to the document, but following this guide will help you get started. Since this is mainly made up of my own experience and, to some extent, Gitea's [Source code] (Https://github.com/go-gitea/gitea), I will listen to feedback on how to improve this part and update it accordingly. If you have some questions or questions, I recommend that you review [how to Generate FAQ] (https://goswagger.io/faq/faq_spec.html). # # Local Run Swaggerui Once your comments are ready, you are likely to test it in your local environment. To do this, you need to run two commands: 1. Generate spec [[Docs]] (https://goswagger.io/generate/spec.html) 2. Serve [[Docs]] (https://goswagger.io/usage/serve_ui.html) This command we used to generate Swagger.json and use Swaggerui: ' Consoleswagger Generate Spec-o./swagger.json--scan-modelsswagger Serve-f=sWagger Swagger.json ' or, if you just want to make it a command: "' Consoleswagger generate Spec-o./swagger.json--scan-models && Swagger Serve-f=swagger Swagger.json ' executes this command, a new tab is opened using [Petstore] (http://petstore.swagger.io/) managed Swaggerui. The server has CORS enabled and attaches the standard JSON URL as a request string to the Petstore URL. In addition, if you use Redoc flavor (-f = redoc), the document will be hosted on your own computer (Localhost:port/docs). # # There are many ways to deploy the generated Swaggerui on a server on a server. Once you have generated the Swagger.json, it should be relatively easy to run. For example, our app is running on Google app Engine. Swagger Spec is generated by our CI tools and is available on the/docs path. We deployed Swaggerui as a Docker service on Gke (Google container/kubernates Engine), which gets swagger.json from the/docs path. Part of our CI (wercker) script: "yamlbuild:steps:-script:name:workspace setupcode: |mkdir-p $GOPATH/src/github.com/orga/ Repocp-r * $GOPATH/src/github.com/orga/repo/-script:cwd: $GOPATH/src/bitbucket.org/orga/repo/cmd/api/name: Buildcode: |go get-u github.com/go-swagger/go-swagger/cmd/swaggerswagger generate Spec-o./swagger.json-- Scan-modelscgo_enabled=0 go build-a-ldflags '-S '-installsuffix cgo-o App. cp app *.template Dockerfile Swagger.json "$WERCKER _output_dir" ' Route: ' Gofunc (d *doc) Dochandler (c context. Context, W http. Responsewriter, R *http. Request) {r.header.add ("Content-type", "Application/json") data, _: = Ioutil. ReadFile ("/swagger.json") w.write (data)} ' Dockerfile: ' dockerfilefrom swaggerapi/swagger-uienv api_url ' https:// Api.orga.com/swagger "'" # # Summary Swaggerui is a powerful API documentation tool that allows you to easily and beautifully record your API. With the help of the Go-swagger project, you can easily generate the Swagger specification file (Swagger.json) required by Swaggerui. In conclusion, I describe the steps taken to achieve this goal. There may be a better way, I will make sure to update this article based on the feedback received. The sample is available on [GitHub] (https://github.com/ribice/golang-swaggerui-example). The Swagger.json generated from the sample is in [LINK] (Https://ribice.ba/goswagg/v1/swagger).

via:https://www.ribice.ba/swagger-golang/

Author: Emir ribic Translator: Fatalc proofreading: Rxcai

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

2,447 reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.