8 ms·
OpenAPI Generator allows generation of API client libraries from OpenAPI Specs
- Arnavion 4y ago>OpenAPI Generator allows generation of API client libraries from OpenAPI Specs It does, but the generated code can be very shitty for some combinations of spec and output language. I maintain Rust bindings for the Kubernetes API server's API, and I chose to write my own code generator instead. The README at https://github.com/Arnavion/k8s-openapi https://github.com/Arnavion/k8s-openapi has more details. The point there about bugs in the spec is not limited to Kubernetes. $dayjob's software product interacts with the Docker daemon's server API so we generated bindings using the Docker spec, but that spec had a bug where some timespan values used the wrong integer type ( https://github.com/moby/moby/issues/39131 https://github.com/moby/moby/issues/39131 ). Luckily we were able to fix them in our generated code because we'd opted to check in the generated code instead of building it dynamically at compile time. The generated code also had a bug in the function for pulling Docker images, because it did not account for the fact that pulling the image can fail at some point after it has started, in which case the HTTP response has a successful status code but the streaming body ends with an error record. We had to edit the generated code to incorporate any error records in the response body as an error in the overall function result. And as I wrote in the "sans-io" section of that README, I also believe the generator's approach of providing an API client that has all decisions made for you, like whether the API is sync or async (in languages where that matters), what HTTP library it uses internally, etc is overly limiting. It means that a user who does not agree with even one of those decisions is prevented from using the entire generated library. In my opinion the part where models/requests can be encoded to bytes and models/responses can be decoded from bytes is separate from the part where bytes are sent and received over HTTP, which is why k8s-openapi only does the former and you can write a thin wrapper to use it with your chosen HTTP client. So basically, the generator exists and is a good starting point when you just want a quick and dirty way to consume an API, but a) you should have a plan for bugs in the spec and bugs in the generated code, b) you should have a plan for generating your own bindings instead of using a third-party library that generated them for you if you don't agree with any of the third party's choice of codegen parameters, and c) you might find hand-written bindings, or a bespoke hand-written generator for that particular spec, worth the investment.
- mooreds 4y agoI talked to a startup ( https://stainlessapi.com/ https://stainlessapi.com/ ) about a service they provide where they take an OpenAPI spec and build good SDKs on top of it. This included making sure they are idiomatic, included examples, handled exceptions (Edit: like if one SDK consumer needs a slightly different thing because they use a different, custom API, not like network or language exceptions) if needed, and some other goodness. I passed for now because they don't have the language support we need and I am not sure if we need their level of sophistication, but others may benefit from talking to them. (I think the founder helped build Stripe's API docs, IIRC.) As we head down our OpenAPI path (https://github.com/fusionauth/fusionauth-openapi https://github.com/fusionauth/fusionauth-openapi has only been built for the last 9 months), I'm very interested in stories like yours. We're very interested in quality SDKs that are easy to update. But since we control the OpenAPI spec for the product, we might have an easier time than you in some ways. Thanks for sharing!
- searchableguy 4y agoI prefer graphql because of this. It's a huge pain to maintain open API files and the generators are of varying quality supporting different specs. They also handle some parts differently in the output. Which generator have you used for typescript? There are 4 of them and all of them have different issues. I find the axios one the most stable but keen to know. How do you also handle refreshing token, incepting request while passing the client through configuration in these? I find interception and changing response breaks some of the client methods without a way to handle the failure. Any example or resources you found useful would be appreciated.
- mooreds 4y agoWe are still early on our journey, but I'll share this post with the Stainless folks (who are further along); maybe they'll chime in.
- aserafini 4y agoIt shouldn’t be a pain to maintain OpenAPI files. The same code you write to validate your request/response should automatically generate the OpenAPI see my comment here: https://news.ycombinator.com/item?id=33221395 https://news.ycombinator.com/item?id=33221395
- nico 4y agoWhat’s the conceptual difference between this and SOAP with WSDLs?
- mooreds 4y agoOuch :) . In concept, not much. Maybe slightly easier to implement? More momentum? Certainly a more modern feel (can't think of the last time I saw someone build a new SOAP service, but maybe that's just the circles I run in).
- cratermoon 4y agoOr for that matter Sun (now ONC) RPC, CORBA, DCOM, DCE, gRPC, or XPCOM?
- faldore 4y agoCorba had the funkiest interop issues
- cratermoon 4y agoError: no error
- faldore 4y agoSOAP (and XSD) were amazingly expressive and capable. They just didn't do enough to balance verboseness, simplicity, and conciseness. Amazing how much work and progress was lost when it was all thrown away for REST/JSON. JSON Schema is great but never reached the level that XSD did.
- ccouzens 4y agoI maintain a project that converts from a specific API mostly documented in XSD to JSON schema. For the specific API I'm interested in XSD and JSON Schema are mostly equivalent. Quite probably it isn't true in the general case. Check out some of the test cases in this directory to get an idea how XSD can be translated into JSON Schema https://github.com/ccouzens/vcloud-rest-openapi/blob/main/transformer/src/parsers/doc/etc/field.rs#L348 https://github.com/ccouzens/vcloud-rest-openapi/blob/main/tr...
- igor47 4y agoI'm also curious about the reverse direction -- can I generate an openAPI spec from my typescript Api? I'd rather write code than schemas.
- jayp 4y agoThis is the best project I’ve found to that for that - https://github.com/lukeautry/tsoa https://github.com/lukeautry/tsoa. Uses decorators mainly. If there are other such projects, please share.
- NonNefarious 4y ago
- aserafini 4y agoThis is exactly how FastAPI/Pydantic in the Python ecosystem works (and also in Django-ninja for Django). You compose types representing your request and response shape. Those types validate the API request and it’s response, and also generate the OpenAPI. Even slight drift between API spec, docs and actual behaviour is impossible in this setup, I couldn’t go back to working any other way!
- twelve40 4y agocan only speak for python on the backend, but have been using auto-generated schema from Django, and an auto-generated typescript client for it on the front end for years now.
- remoquete 4y agoSure, though that goes against the API first design principles that OpenAPI seeks to enable. It also results in poorly documented, often garbled OpenAPI specs. Code-generated specs simply cease to be effective as contracts. https://swagger.io/resources/articles/adopting-an-api-first-approach/ https://swagger.io/resources/articles/adopting-an-api-first-...
- rattray 4y agoThis is something we hope to build relatively soon at Stainless, inspired by Stripe's in-house Ruby API DSL. I think what you're asking for is the right approach.
- wizwit999 4y agoAlso check out Smithy from AWS (https://github.com/awslabs/smithy https://github.com/awslabs/smithy), the code it generates is much better. It's influenced by the new AWS SDKs so it has generator support for Rust.
- mooreds 4y agoDoes smithy support OpenAPI? Doesn't seem like it does (found a reference to smithy -> openAPI support, but not the reverse).
- mooreds 4y agoI looked at Smithy further and it seems interesting but nascent. For example, all client code generators are in "early development": https://awslabs.github.io/smithy/2.0/implementations.html#client-code-generators https://awslabs.github.io/smithy/2.0/implementations.html#cl...
- wizwit999 4y agoIt's actually used for the new AWS SDKs but yeah fairly new.
- Grokify 4y agoDisclosure: I'm a contributor to the project. OpenAPI Spec and auto-generated API clients are very useful when multiple languages need to be supported, like when running a developer program. I've worked at companies that both use OpenAPI Generator for official clients and ones that wrote our own tools for API client SDK generation (with different design philosophy). I've used a number of generators myself to compare and submitted fixes / enhancements to OpenAPI Generator. I used the Go client generator a while back and compared it to others, and recently started using the Crystal one. To get the most the project, the following is useful: (a) need to support multiple languages, (b) ability to update the generator's code, both in Java and templates (Mustache or Handlebars), and (c) ability to discuss design in GitHub issues and the Slack channel. The nice thing about OpenAPI Spec is that there is an ecosystem of tooling to support it, including rendering API references (HTML and PDF), API explorers (HTML pages to execute API calls), API clients, etc. But there is a learning curve. For writing specs by hand, I use and favor the Stoplight Studio IDE ( https://stoplight.io/studio https://stoplight.io/studio ). For programmatically analyzing and editing specs, which is especially useful for finalizing auto-generated specs, I've built an OpenAPI Spec SDK library to make this easier ( https://github.com/grokify/spectrum https://github.com/grokify/spectrum ).
- NonNefarious 4y ago
- mooreds 4y agoHi! First, thanks for this. It's a lot of work to support OSS and I appreciate the effort of you and the team. Second, is there any way for new users to determine the maturity of each of the (many) generators available? I haven't seen it in the documentation or the github repo, but maybe I missed it?
- thraizz 4y agoWe used this to generate api functions for our react application and then discovered and switched to Orval. It generates react query functions instead of „normal“ axios functions. Also it has support to generate a complete api mock with msw + faker.js - really nice.
- solarkraft 4y agoThis looks cool. Previously I was only aware of this blog post regarding React Query hooks from OpenAPI schemas: https://xata.io/blog/openapi-typesafe-react-query-hooks https://xata.io/blog/openapi-typesafe-react-query-hooks I take it that you’re happy with Orval. What are the biggest downsides?
- la55u 4y agoThe downside is it's pretty hard to maintain (the implementation is primitive string manipulation). Another cool tool I found is `rapini` but sadly it has no MSW support.
- iddan 4y agoTried to use it a couple of time to generate a TypeScript client for my Nest backend and it didn't work…
- yowmamasita 4y agoThis is what we use at work for the same stack. What problem did you face?
- xvilo 4y agoI'm not really positive about the community made generator. The spec itself is great, but that's where it stops. Code quality is low of the generated clients and servers, the handlebars templates makes it hard to develop for and don't get me started about the PR reviews. Basically nothing happens. We've given up and started to create our own generator. Even this is a hard thing to do as the available parsers in our language are horrible too.
- Grokify 4y agoWhat is your language? I've found kin-openapi to be very usable for Go: https://github.com/getkin/kin-openapi https://github.com/getkin/kin-openapi
- alexanderdavide 4y agoUsed OpenAPI Generator a few times and I'm happy with it. In my latest React Native project I generate the API client and inject functions into React Query. I know there's Orval that aims to generate React Query right away but I wasn't happy with its developer experience.
- solarkraft 4y agoWhat are the DX issues you found with Orval?
- simplesager 4y agoDisclosure: I'm a cofounder of this startup We've been building client sdks as a service at Speakeasy (https://www.speakeasyapi.dev/ https://www.speakeasyapi.dev/). API developer experience today in REST struggles because the openapi generators are buggy and generate machine-readable stubs rather than ergonomic SDKs. We ended up building a new generator from ground up focused on ensuring we could capture idiomatic features specific to each languages. For API consumers our goal is to provide a best in class dev ex and taking the burden off of having to rewrite common boilerplate like pagination and retries. For API producers you get to focus on building your API and not have to worry about table stakes features for your users. We started a closed beta programme recently. Shoot me a message at sagar@speakeasyapi.dev or come chat with us on slack if you want to early access! https://join.slack.com/t/speakeasy-dev/shared_invite/zt-1df0lalk5-HCAlpcQiqPw8vGukQWhexw https://join.slack.com/t/speakeasy-dev/shared_invite/zt-1df0...
- PebblesHD 4y agoGreat to see other engineers focusing on this space. I’ve spent a good chunk of my career writing in-house clients for various business critical APIs and have always had a giggle that our self-made ones were often far nicer to use than anything on the market but was always disappointed that due to a variety of corporate constraints they will never see the light of day. I can see a big benefit to bespoke hand-rolled clients with a solid developer experience so keen to see where you guys go!
- simplesager 4y agoThanks ! let us know if you'd want to try it out, happy to give you early access or generate a few SDKs for you.
- miga 4y agoIf you want to generate OpenAPI specs from HTML web pages, see here: https://www.migamake.com/projects/hurl.html https://www.migamake.com/projects/hurl.html
- puika 4y agoI was very excited about this project when I first encountered it as it seemed to be the best centralized community-driven way to generate code for multiple languages and supporting v3. The more time I spent with it the more disappointed I became. The reason why you are forced to write Java and write your own generator alongside the rest of the project is unclear to me. Extending the mustache templates is a pain (and handlebars experimental). Every little change you want to make requires you to change the library itself. Most generators I looked at (TS clients, Go clients and servers, Python clients) generated dubious code and project structures for actual usage. My current approach to deal with all of this e.g. in Go server generation is to output to some temp directory and have (long) post generation scripts parse the current and generated AST to (1) restructure to my liking, (2) merge changes where appropriate (the generator would overwrite your code otherwise) and (3) generate helper files with Go templates, which are actually pleasant to use. (2) is necessary if you don't want to have generated maps all over the place to access the handler for this route, the middleware for this other one, etc. You won't have to edit generated files, but good luck figuring out what's going on. As long as you clearly state what methods can be edited and which ones are always replaced with the generator output you should be fine with (2). You may be thinking: > why do all of this instead of writing your own generator? to which I answer: Touché.
- CodeWriter23 4y agoIsn't this the case with all Open Source, that if one really wants to extend something, one must first get into the same mindset as the original designer and understand "their way" of doing it?
- rattray 4y agoFellow "wrote my own generator" person here (I built the codegen system Stripe uses to generate their API client libraries). Sounds like you've got a pretty neat system too, hadn't thought of some of these approaches. We had a similar story – after looking at the OpenAPI Generator and other options, we ended up making our own in JS from the ground up, more or less (it used the internals of prettier to generate pretty code, especially example snippets for docs, across languages). I'm now starting a company (https://stainlessapi.com https://stainlessapi.com, mentioned by OP elsewhere on this thread) to solve this problem more generally. If you ever get tired of maintaining this system (which may not happen, it does sound fun/interesting) or want broader language support, and are open to a commercial solution, drop me a line: alex at stainlessapi.com (open invite of course – and also always happy to just chat codegen things, it's a neat little niche)
- mihaitodor 4y agoI tried using it as a Go code generator (I only needed structs and marshaler / unmarshaler helpers), but it ended up being way too difficult to use and I couldn't get it to work properly. After a bit of searching, I bumped into Deepmap's implementation https://github.com/deepmap/oapi-codegen https://github.com/deepmap/oapi-codegen which works great. They even added support for oneOf, anyOf and allOf which makes things a lot easier.
- mooreds 4y agoThat's awesome, thanks for sharing! Would love to know if anyone else has any language specific SDK generators they'd recommend, similar to the Deepmap implementation, but for another language (ruby, python, c#, java, etc).
- deleted 4y ago[deleted]
- jamietanna 4y agoOne of the maintainers here, thanks for sharing and that it's been great for you
- mihaitodor 4y agoHappy to help and thank you for the great work! :)
- steve918273 4y agoI’ve been trying to use this to generate sane, idiomatic Kotlin models, and am so far a little frustrated by the choices the generator makes - especially with regards to how to represent `anyOf` And `allOf` constructs. Has anyone had success with generated Kotlin? I’m also curious if there are other Kotlin generators out there.
- treis 4y agoIt's been a pain for us too. Personally, I don't really see the point of type checked request/response models. Theoretically, I can see how it's nice but ultimately the source of truth are the domain models on either side. If you do something wrong you'll either see a 400 or be unable to build models from the response. And since the compiler can't really type check across the API boundary you still need to account for unexpected values. The difference is that the failure happens in ugly auto generated code instead of within your code where it is more easily handled.
- thesnide 4y agoSuch generated code is my very definition of "hell is paved of best intentions". As in the end, you'll spend more time fighting with the tool to generate the code you want than writing it yourself. That, and bloat.
- asim 4y agoWe ended up building this in-house like most mentioned. Speakeasy and Stainless are productizing it. Our goal was just to make it available for APIs we were offering to others (https://m3o.com https://m3o.com).
- solarkraft 4y agoI’ll soon discover whether doing this is a good idea or not. Will it encourage good practices or hinder them? Remember that you don’t have to generate both your server and client APIs from the schema (schema first). Many API servers (I’m particularly aware of OpenAPI and Sanic from Python land) allow you to export the OpenAPI definition from your existing API (code first).
- ccouzens 4y agoI've found apenapi generated clients very helpful with statically typed languages and very unhelpful with dynamic languages. For dynamic languages I'd recommend using an http library directly. Consider the code without a generated client code: client.get("/hello") And the code with a generated client client.hello() In a dynamic language they're about the same. But in a statically typed language - I know the second case is calling a route that exists - The response is typed - If there is request data or query parameters the language helps me use them correctly - My editor displays documentation about the request if I hover over it, including if it has been deprecated
- spacether 4y agoThe v6.2.0 python client uses type hints everywhere so model property access gives typed results Endpoint inputs are typed. Endpoint responses are typed so you know what deserialized body models you are getting back. Have you tried it?
- lucasyvas 4y agoI recommend steering clear of this project entirely - if you really care use something like gRPC instead. Every time I've used it, it has failed spectacularly to generate models as promised and I've had to write the clients by hand anyway. There are just far too many bugs in the respective language generators and it all seems to fall apart when you start using anyOf, oneOf, etc. It only takes a quick stroll of the issues to find that many features of OpenAPI aren't supported in certain generators, so it's a total waste. I do still like OpenAPI as a design tool and it produces very human readable documentation as well, so it's still useful if you intend to only use it just for that. Just keep your expectations very low when it comes to generation. Edit: I forgot to mention that clients are subject to breakage if you change the names of models - model names are not actually a part of the contract in my opinion - only the protocol aspects should be (path, params, body, etc.). I don't see how they would solve this but it's a major pain. If you imagine writing a client yourself, it would not break if you tweaked a model name, so this is a huge downside. I have a scenario where the model names are only there for branding (a numerical enum that has a human readable model name), but are now being hardcoded into the spec in a way I didn't want. I really didn't want to give the models generic, unreadable names in the docs but that seems to be what OpenAPI wants me to do.
- cies 4y agoOAPIv3 (fully spec'd/schema'd REST+JSON APIs) is nice, and the generators are important, yet as many point out "not always that great". There's an alternative technology: GraphQL, which has generators too! Here a PoC of mine demo'ing an architecture in which the backend is very low code (mostly due to Hasura), and most of the app's code is in the frontend: an Elm app with generated type-safe Elm-bindings to the GraphQL backend. https://github.com/cies/low-code-backend-dockered https://github.com/cies/low-code-backend-dockered
- bdcravens 4y agoOff-topic, but you may want to chill on the emojis in the README. That's a marketing smell.