DEV Community

Play Button Pause Button
Kevin Gilpin for AppLand

Posted on • Updated on

How to auto-generate detailed Swagger/OpenAPI for all your Rails routes

Welcome back to my RailsConf 2021 presentation recap! Check out Part 1 and Part 2 in case you missed them last week. This post recaps the second demo I gave as part of my talk. Using rswag and the appmap_swagger gem, I showed RailsConf attendees how to auto-generate Swagger files instead of manually writing them.

The Swagger UI takes JSON or YAML files and generates an interactive catalog of your web services. The catalog contains routes, methods, status codes, parameters, request body, authentication methods and more. With Swagger, you can:

  • See your whole web services catalog and actively interact with all of the API functions
  • Debug your webservices in a very granular way
  • Observe your web services test coverage visually
  • Diff the web services changes by committing your Swagger YAML and comparing across versions using standard source diff

How Swagger works

Writing Swagger files -- and keeping them accurate and up-to-date -- is a real challenge, so here are two ways of auto-generating these files:

  1. With a gem called rswag Swagger can be auto-generated from test cases. Rswag ensures a valid Swagger file thanks to assertion checks performed by rswag, and it’s very customizable.
  2. With appmap-swagger Swagger can be auto-generated from AppMap files, which are recorded from test cases. appmap-swagger also ensures a valid Swagger file, but achieves more complete API coverage faster. You also don’t need to learn as much about the OpenAPI format to use appmap-swagger.

You can watch this portion of my RailsConf talk in the video clip above. If you want to follow along in the code or look it up later, I’ve created a branch called swagger within the Land of Apps fork of the Rails Sample App. Check it out, and let us know what you think in the AppMap Discord!

Coming up next... In the fourth and final installment of this blog series, I’m going to recap the remaining demo of my RailsConf talk: how to auto-document database schemas.

Discussion (1)

Collapse
max_lapshin profile image
Max Lapshin

I see a lot of generators of spec from code and it is a biggest misunderstanding of the idea of openapi.

  • what program do you write?
  • I have no idea, will launch and take a look.

Idea of openapi is design-first approach. You write specs, discuss them with all stakeholders and then generate code from these specs.

Mechanical code generation will give you confidence and tell for sure that code is working according to specs.

When spec is generated from api, than any minor fix in code can break contracts and no test will fail.