r/golang • • 12d ago

help OpenAPI Specs

How do you handle OpenAPI in go?

I'm coming from C# .Net and Laravel, normally these auto generate the specs, but in go I haven't found the standard way of doing this, the golang way.

I understand there are packages you can use to do this by writing comments/annotations, which is very tedious.

Is there a proper way to do this, or do even go developers do this at all?

Your response is very welcome, especially from those working in companies with somewhat large code base.

Thank you!

Edit: Thank you all for your feedback and recommendations, but I'll stick to ASP.NET Core for now. Maybe in future when I have time I'll explore Go again, it's a beautiful language.

62 Upvotes

39 comments sorted by

9

u/Helpful-Educator-415 12d ago

I don't write Go much anymore, but Huma seems to be the most popular.

4

u/Emotional-Ask-9788 12d ago

Let me check that out, thanks!

6

u/bonzai76 12d ago

Have a love/hate with Huma for sure but it’s 300% better than writing documentation

1

u/Emotional-Ask-9788 12d ago

What are you currently using?

5

u/Helpful-Educator-415 12d ago

Rust, with ConnectRPC + Protocol Buffers. :)

2

u/soullessredhead 11d ago

Protobuf and gRPC is a breath of fresh air after working with REST for so long.

1

u/Helpful-Educator-415 11d ago

Tell me about it!!!!

43

u/radio-nl 12d ago

In C# it’s usually code first, in Go - SPEC/contract first is the preferable option. IMHO, at some point you realize that it’s always better to have a clear plan before even starting to implement, therefore the latter approach seems more mature.

Here’s a project that might be of a service - https://github.com/ogen-go/ogen

6

u/ModVirus 12d ago

Ogen is the way yes 👍

7

u/1Soundwave3 12d ago edited 12d ago

Yeah, that's why I see Swagger on every C# project and almost never on Go projects.

As I always say, if it's not automated, it's not done.

I'm so glad we have AI now. The biggest thing that kept me, a C# developer, from fully embracing Go as a language for personal projects, was how manual everything was.

Well, since early 2025 I created 2 C# projects and about 30 Golang projects and I feel happy. I guess creating a proper Swagger spec should be on my agent's checklist when I finally decide to integrate with somebody.

2

u/Little_Fawne0 11d ago

that's an interesting point about code first versus spec first between the two languages. i can see how having a clear contract upfront would be beneficial.

2

u/Marknumskull 11d ago

Yeah spec first and auto gen the endpoints is the way to go 💪

1

u/Schmatter_Raphiqui 11d ago

Go not having runtime attributes like C# does is a big reason code-first feels so clunky here without those magic comment blocks

18

u/BornSpecific9019 12d ago

personally prefer spec first

- write oapi spec
- use openapi-codegen to generate
- use CI pipeline to check if generated code is up to date
- implement the generated interfaces (preferably with strict mode)

6

u/unhappylurker 12d ago

oapi-codegen/oapi-codegen is what I would use. Write the spec first, then generate the code using spec

5

u/IncomeOk7237 12d ago

Coming from ASP.NET I had the same reaction. If you really want code-first, Huma is the closest thing to Swashbuckle, it builds the spec from your actual request/response structs so it can't drift from the handlers. The comment annotation route (swag and friends) is the one I'd avoid, the comments go stale the first time someone renames a field and nothing fails.

That said spec-first grew on me. The nice side effect is that API shape changes show up as a yaml diff in review before anyone writes Go, which is way cheaper than arguing about it after the handlers exist.

1

u/infostack0 11d ago

To be fair it’s not especially hard to have a CI check or git hook to make sure things are in sync before PR merge or commit.

1

u/IncomeOk7237 11d ago

Fair point. A CI step that regenerates the spec and fails on a non-empty git diff covers most of it. My gripe is just that you find out at PR time instead of while writing the handler, but if the team actually sets that check up it's basically a solved problem.

1

u/infostack0 11d ago

Generally what I see is a makefile target (I would prefer a mise recipe) that does it so you can run locally, and the CI check runs the same make target so it’s in sync.

Devs are then free to set up their own git hooks locally if they can’t remember to run checks before push but I think most people just get in that habit when they get burned by waiting awhile for CI to fail on something they could have checked beforehand.

1

u/IncomeOk7237 11d ago

Yeah, that's the setup I like too. One make (or mise) target that both CI and local call means there's a single definition of "in sync", and hooks stay optional for whoever wants them. Waiting 10 minutes for CI to fail on a stale spec is pretty much how everyone learns to run it first.

4

u/dariusbiggs 12d ago

Do you want specification first, or code first for the authorive source?

Code first is Huma v2 and a few other options.

Specification first is pretty much everything else like swaggo, that is code generation from the schema.

3

u/Ok_Manufacturer_8213 12d ago

For Code first chi with huma is great!

3

u/itaranto 12d ago

Anything but the annotation/comment based solutions. It's the worst of both worlds. I remember using swaggo for this, you end up adding lots of comments and struct tags all over the place, it gets pretty complex pretty fast. It has the same downsides as witting the spec manually, there's no guarantee those comments/tags are (fully) in sync with the code. At that point you are better off writing the entire spec manually, which is bad, but at least it's less annoying.

Now, the ideal scenario would be to either use a spec-first or a code-first approach. I don't like much the idea of generating such a critical part of a server, code generators tend to add too much bloat an unnecessary stuff as they need to be generic.

So I think code-first theoretically should be better, but I haven't tried yet. I've heard nice things about Huma.

3

u/Feeling-Row8973 12d ago

write the spec in YAML first and generate handlers with oapi-codegen. Trying to infer it from Go structs or comments results in brittle code that fights you every time you add a header, validation rule, or complex schema.

5

u/gomsim 12d ago edited 12d ago

We do spec-first. Write the openapi spec and generate the code with oapi-codegen. I kind of hate it. So much of the generated code is incompatible with the stdlib i various ways. And openapi-specs invite structures like inheritence which makes the generated code very non-intuitive. Recently we tried the non-strict mode, which is better, but at this point it's not that big of a difference to just not generating anything at all. Personally I prefer to not generate one or the other, but that has obvious downsides too of course, hehe,

I haven't tried huma, but it sounds like that would yield a smoother experience.

3

u/deserving-hydrogen 12d ago

I have the same workflow but haven't found the incompatibilities you mention. Do you have any examples?

1

u/gomsim 10d ago edited 10d ago

Right! Sorry for any ugly code examples, I'm writing on my phone.

When using strict mode middleware don't follow the typical middleware signature of func(http.Handler) http.Handler, but rather takes an operationID and a custom generated type as input. This not only makes it incompatible with normal Middleware, it also binds the middleware to this specific generated codebase since it takes type parameters that are generated from the spec. Thus middleware are no longer portable between codebases. Normal middleware can be passed in via a constructor parameter somewhere, but then you have two ways of passing middlewares and they are also not applied in the same way at the same time, so you need knowledge of the internal parsing flow of the generated code to understand what happens when, which has led to subtle bugs. In non-strict mode only normal middleware are possible, which is fine (probably good), but then they are only possible to be applied globally across a generated handler (struct with handlerfunc methods). To apply them more granurlarly you need to bypass the generated endpoint-handler mapping and and that point the only thing you've really gotten out of oapi-codegen is the generated DTO types and path- and query variable parsing since you map endpoints yourself and unmarshal request bodies yourself.

Also, with both strict and non-strict mode the handler functions of the generated code don't follow the http.HandlerFunc function type. There are ways of working around this but it's complication for very little gain.

With strict mode, since openapi-spec invite to strange inheritance structures the generated code is a convoluted mess of "visit" patterns. Handlers return interfaces, not concrete types. These interfaces have functions VisitXXX which basically resolves them into concrete types based on discriminators, which is just a very strange pattern to see in a go codebase and very hard to follow. I apologize in advance here because I cannot bring myself to remember an understanding of this following part, but related to this visitor pattern we needed to write custom templating code in yaml to make oapi-codegen generate some specific types' visitor methods correctly because of the way "we" wanted the inheritence to work.

Besides this, oapi-codegen didn't have sufficient xml support that we needed for a specific project so we needed to write the body unmarshalling anyway.

I've just written the stuff that is on the top of my mind, perhaps there is more, perhaps not. But at some point I asked myself what I'm actually gaining from the loss of control that oapi-codegen gives me. Because it sure as hell isn't less work. I know that it of course binds the openapi-spec to the code, and that is a powerful thing in itself, but it sure as hell isn't smooth.

Edit: remembered another thing. Generated code defaults to using pointers for optional parameters. This should never ever be the default in Go. Pointers in that regard are only necessary if the distinction between an empty and a non-set variable is meaningful, which in most cases it isn't. This leads to unnecessary java-style nil-checks all over. Avoiding this requires extra go-specific control properties in the openapi-spec to basically tell the generator to generate your code in a specific way. The same goes for naming of parameters. Special properties are needed in the spec to make fields in the generated structs follow Go naming convensions.

-3

u/1Soundwave3 12d ago

Are you guys still using codegen? I mean, AI exists and is usually mandated by management. You can tell it to generate your code and your OpenAPI spec all in one go.

4

u/WolverinesSuperbia 12d ago

I use swaggo/swag. Annotations in comments, tool for formatting and regeneration.

1

u/22goodnumber 12d ago

I'm a big fan of fuego (https://github.com/go-fuego/fuego). It uses the new(-ish) go generics so method signatures define the inputs and outputs and it generates swagger/open-api docs like what you're used to. Lots of options to customize the documentation as well.

1

u/iabqle_bis94 12d ago

Before AI, I used swag-go by adding comments; these days, I ask AI to generate the openapi-v3.yaml first, and once I review it, I ask my agent to write the api.

1

u/Open-Adhesiveness-86 11d ago

if you do go code-first with huma, check what version your consumers need before you commit. it emits 3.1 by default and a lot of client generators still choke on that, especially anything older built on openapi-generator. huma does serve a downgraded /openapi-3.0.yaml, but the conversion is lossy around nullable, so diff the two before you hand it to a frontend team.

1

u/fahim-sabir 11d ago

Can’t believe that even now people are going code first. Somewhat defeats the point if you ask me.

1

u/Heavy-Blacksmith-620 11d ago

I use https://github.com/oaswrap/spec . This is code first, and has adapter for most popular api library.

1

u/Turbulent_Ad9831 11d ago

Go doesn't really have an annotation magic culture like .NET or Laravel, so trying to generate OpenAPI from struct comments with swaggo usually turns messy fast. Most Go teams I've seen go spec-first with oapi-codegen so the YAML stays the source of truth and the server stubs stay strictly typed.

1

u/sonicLodge91 9d ago

had a swag ci check wired on one service, the other two drifted for omnths before anyone noticed

1

u/autogenusrz 9d ago
  • Write Spec first
  • Lint Spec in CI
  • Implement

1

u/dariusbiggs 1d ago

So you want code first or schema first.

  • openapi-codegen for example is schema first
  • Huma v2 is code first

There are others in each category with more or less automation.

1

u/moodyindie 8d ago

Same diff check here, my pain is the client lib, every spec tweak reshuffles the generated types, how do you keep consumer churn down?