danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
1.71k stars 134 forks source link

Generating Huma Code from OpenAPI Spec #439

Open srilman opened 2 months ago

srilman commented 2 months ago

Is there any way to generate a REST API using Huma from an OpenAPI spec? The docs mention the opposite, using Huma and oapi-generator to reconstruct a server without Huma. However, I have a use-case where I have an existing OpenAPI spec that I want to implement while retaining some of the other benefits of Huma (validation, docs generation, etc) without needing to copy everything over.

I wasn't sure whether to ask this question in this repo or the oapi-generator repo. I does seem like more their alley, but they may not store all of the spec info for codegen.

danielgtaylor commented 2 months ago

@srilman thanks for the question! Unfortunately that isn't possible at the moment. Huma does not generate anything from OpenAPI specs itself. It would be possible to create a template for other code generators that spits out Go code using Huma, but I don't think that exists at the moment. As a side note, it's also a bit complicated because Huma supports most but not all of the OpenAPI features, and some OpenAPI documents can be written in a way that makes it hard to generate sane Go code (for example using oneOf/anyOf/not or complex branching, constants, etc).

Anyway I'd be happy if someone wants to build this, otherwise you may just have to manually convert it to Go code for the time being.

srilman commented 2 months ago

Good point about the complex spec features (oneOf, anyOf, etc), I didn't think about that. Thankfully, I can leverage another Go library that has some of these parts already implemented.

I think for the time being, I'm going to write a small Python script using https://github.com/Dorthu/openapi3 to generate a template, and then fill in the blanks for anything too complicated. Once I have something working, I'm happy to share a Gist.