Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically generate RESTful API documentation with Swagger #155

Open
ndbroadbent opened this issue Nov 19, 2014 · 79 comments
Open

Automatically generate RESTful API documentation with Swagger #155

ndbroadbent opened this issue Nov 19, 2014 · 79 comments

Comments

@ndbroadbent
Copy link

One thing I really like about go-restful is their built-in Swagger integration. Check out the example project: https://github.com/emicklei/mora#swagger

Some things I really love about Gin is the focus on performance, and overall, it just seems like a much better designed framework. However, I think that auto-generated documentation with Swagger is pretty awesome. It makes it easy for new engineers to get up-to-speed quickly by reading through the docs, and I especially love the way you can auto-generate API clients for lots of different languages.

I'm not sure how involved this change would be, I'm not sure if this could be done as an extension. But we could probably take lots of inspiration from (or just copy) the swagger code from go-restful (MIT licensed).

Anyway, this is not a huge priority for me, just a nice to have.

@rogeriomarques
Copy link

+1

1 similar comment
@phalt
Copy link

phalt commented Dec 2, 2014

+1

@redstrike
Copy link

+1, swagger is very useful for API development

@matejkramny
Copy link

👍

@javierprovecho javierprovecho added this to the 0.6 milestone Feb 4, 2015
javierprovecho added a commit that referenced this issue Feb 4, 2015
- Reorganize roadmap for v1.0, done in the bottom, to do at top.
- Added request for #155, swagger support.
@javierprovecho
Copy link
Member

@phalt @redstrike @matejkramny @rogeriomarques @ndbroadbent I'll add support for it with v0.6 in mind. Thank you for submitting this request.

@salimane
Copy link

salimane commented Feb 5, 2015

+1

@javierprovecho javierprovecho removed this from the 0.6 milestone Mar 9, 2015
@colthreepv
Copy link

I'm gonna raise the biddings on this issue, Ok for Swagger, but why not RAML?
In my personal experience using both swagger and raml barebone, the latter has a better explained specification and has a more pragmatic approach.

I'll explore what can be done with my limited golang skills, and keep you posted

@colthreepv
Copy link

One of the main concerns in thinking this feature out, is design this swagger/raml feature producing a base json/raml document that can be extended to let the user exploit the full-feature set of their API specifications.

I hardly seen that in other frameworks, but I'm hoping someone could propose some input regarding this

@njuettner
Copy link

+1 for swagger support

@itsjamie
Copy link
Contributor

I'm surprised there isn't someone who has created a parser that looks at an AST + attached routes for net/http to generate Swagger/RAML style documentation.

If it isn't a project, perhaps that would be the better method of implementation for this? Rather than having it part of Gin core, if it was a separate binary that scanned a package?

@colthreepv
Copy link

I think to externalize API documentation, gin.router should be exported (so Router).
Moreso, I think model validation should be expanded before implementing API documentation, since there is a big difference between the vastity of API validation options and gin ones.

@DustinHigginbotham
Copy link

Noticed Swagger support was on the README checklist for V1. That seems to be gone now. Should we not have our hopes up for this being released?

@manucorporat
Copy link
Contributor

@dustinwtf We do not need swagger support in 1.0.
1.0 is about having a stable API, production-ready and performance.

Once 1.0 final is reached, we can focus in features. Also, I do not think the swagger support should be part of Gin core. Probably a different package.

@DustinHigginbotham
Copy link

Agreed! That's definitely a good focus. Just wondered considering it was there and disappeared.

@nazwa
Copy link

nazwa commented Jun 6, 2015

Is there an easy way to get all the registered routes now? Like a map of url -> handlers or something.

@manucorporat
Copy link
Contributor

@nazwa no, we need to implement it. Two solutions:

  1. Iterate over the trees and collect the routes.
  2. Save the routes in a separated slice (only for documentation purposes)

While the second way is the easiest to implement it adds a unneeded overhead and complexity all over the place. So I would try to iterate the trees, it can not be that hard.

*Engine should have a method called Routes() []RouteInfo or something like that. We do not want to expose the trees directly.

@manucorporat
Copy link
Contributor

Also, since the router is not longer dependent of the HttpRouter package, we have access to all the info.

@manucorporat
Copy link
Contributor

something like this, I do not have time to do it just now. If anybody is interested, please create a PR!!

func (engine *Engine) Routes() (routes []RouteInfo) {
    for _, root := range engine.trees {
        routes = iterate(routes, root)
    }
    return routes
}

func iterate(routes []RouteInfo, root *node) []RouteInfo {
    for _, node := range root.children {
        routes = iterate(routes, node)
    }
    if root.handlers != nil {
        routes = append(routes,root.path)
    }
    return routes
}

@nazwa
Copy link

nazwa commented Jun 6, 2015

Yea, something like this would be perfect. I'll try to have a proper play with it in the evening, as it definitely would be useful in the long run.

@manucorporat
Copy link
Contributor

@nazwa @dustinwtf @ndbroadbent 45dd777

@manucorporat
Copy link
Contributor

router := gin.New()
router.GET("/favicon.ico", handler)
router.GET("/", handler)
group := router.Group("/users")
group.GET("/", handler)
group.GET("/:id", handler)
group.POST("/:id", handler)
router.Static("/static", ".")

fmt.Println(router.Routes())
[{GET /} {GET /users/} {GET /users/:id} {GET /favicon.ico} {GET /static/*filepath} {POST /users/:id} {HEAD /static/*filepath}]

@manucorporat
Copy link
Contributor

Here's a proposal for auto API documentation:

  • engine.Routes()
    returns a list of the RouteInfo(method, path, handlerName)
    {"GET", "/users", "main.usersHandler"}

  • beego special comments:

    // @Description get all users
    // @Success 200 {object}
    func usersHandler(c *gin.Context) {
    // ..
    }

The swagger generator will use the information from the comments + engine.Routes() to generate the documentation.

@DustinHigginbotham
Copy link

This is perfect, @manucorporat! When do you see this being merged into master?

@manucorporat
Copy link
Contributor

@dustinwtf done! 451f3b9

@zserge
Copy link

zserge commented Jul 6, 2015

@manucorporat Looks great, thanks!

Is there any reason to return the handler function name as a string, not as a Func pointer?
If I understand it correctly - the final goal is to find the comments before the functions and parse them to generate Swagger/RAML docs? Probably the file name and line number would be more helpful (like returned by the Func.FileLine). Then the parser could just read the lines above it.

@manucorporat
Copy link
Contributor

@zserge A pointer to a function is too low level, in my opinion, a high level API (like Gin) should hide low level details, it makes everybody's code safer. For example: if the middleware API would allow to jump between handlers and do crazy things, the whole community of middleware would be more error-prone and unsecure.

I like the idea of providing the filename and line, that's why I created the RouteInfo struct, we can add new fields in a completely backcompatible way! what about FileName string and FileLine uint?
https://github.com/gin-gonic/gin/blob/master/gin.go#L37-L41

@lpxxn
Copy link

lpxxn commented Jan 9, 2018

+1

1 similar comment
@anasanzari
Copy link

+1

@miketonks
Copy link

I'm interested in this idea, and I made a middleware using @savaki 's swag library, that adds a validation middleware. This ensures that api calls have valid params based on the defined spec.

https://github.com/miketonks/swag-validator

Feedback welcome.

@chinajuanbob
Copy link

+1

2 similar comments
@infiquanta
Copy link

+1

@rhzs
Copy link

rhzs commented Apr 14, 2018

+1

@Pokerkoffer
Copy link

any updates on this? Would love to see the swagger api description page within gin

@kostiamol
Copy link

+1

1 similar comment
@ukyiwin
Copy link

ukyiwin commented May 3, 2018

+1

@schrej
Copy link

schrej commented May 3, 2018

Can everyone please stop spamming +1 all the time? Just react on the issue and use the "Subscribe" button on the right. I don't want to klick on the notification to see the newest comments and then just read +1 every time. GitHub added those features for a reason. Use them.

@kostiamol
Copy link

@schrej You are right, but I guess we did that in order to utterly highlight the importance of the feature 😉

@thinkerou
Copy link
Member

personally, I am using https://github.com/swaggo/gin-swagger thanks @easonlin404

@frg
Copy link

frg commented Aug 23, 2018

@thinkerou You'll encounter a lot of limitations when you get to base models, custom types etc. If it's a small project gin-swagger is fine though.

@thinkerou
Copy link
Member

@frg thank you for reminding, I also use it for personal small project right now.

@stoicskyline
Copy link

Has anyone found a favorite approach to this?
Whether it is @verdverm 's custom solution or using a package like https://github.com/savaki/swag

@douyacun
Copy link

hello world!

@tunglv-1933
Copy link

Hi everyone,
Has this done?

@nikzanda
Copy link

+1

@miketonks
Copy link

@yjbdsky
Copy link

yjbdsky commented Dec 20, 2022

+1

@w4-hanggi
Copy link

I really love the concept of Fast-API which can auto generate swagger.
But I don't like building API server with Python, yet.

https://fastapi.tiangolo.com/

@alswl
Copy link

alswl commented Nov 16, 2023

I'm using https://github.com/caicloud/nirvana to generate swagger automatic.

But nirvana is not continued.

@LinuxSuRen
Copy link

I'm wondering if it's possible to generate the e2e testing automatically.

@Will-Mann-16
Copy link

I've developed an implicit OpenAPI generator called astra that will take in your gin configuration and generate an OpenAPI 3.0 specification. Hopefully this helps solve the issue above.

@danielgtaylor
Copy link

I'll point out that my framework https://github.com/danielgtaylor/huma is loosely based on FastAPI and able to provide OpenAPI & JSON Schema on top of Gin (and other popular routers). It provides a bunch of useful features and there's a simple 5 minute tutorial to get you started.

Here's the tutorial code converted to use Gin and runnable in the Go playground:
https://go.dev/play/p/KVF-QCAuvDd?v=gotip

Hopefully this helps somebody.

@ctfrancia
Copy link

this was opened 10 years ago. I know that there have been 3rd party solutions, but, personally I would prefer a gin solution to prevent any breaking in the future

@satokenta940
Copy link

Swagger is indeed a solid choice, but I'm currently using Apidog for automatic document generation. One of the aspects that really attracts me to Apidog is the aesthetic appeal of its UI.

@wangxin688
Copy link

bulit-in support for generate openapi.json/yaml is definity great feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests