rswag - handing unsupported OpenAPI DSL
Once uncommon, APIs are part of any decent application built today. APIs usually communicate with a single server. However, you sometimes need to speak with a different server or the same server through a proxy. How would you document this if you use Rswag to generate OpenAPI 3 and Swagger 2 compatible documentation?
Requirement
Assume your domain name is example.com
, and your API is hosted on api.example.com
. Assume that you are including an endpoint that accepts card details. To simplify PCI compliance, you use VeryGoodSecurity to tokenize card data. This route is going to be cards.example.com/v1/cards
.
The generated YML will have to look similar to:
servers:
- url: https://api.example.com
paths:
/v1/cards:
post:
description: Link a card to my awesome app
servers:
- url: https://cards.example.com/v1/cards
description: Path to tokenization service reverse proxy for PCI compliance
Unfortunately, Rswag doesn't support the property to add servers - Ref Rswag spec.
Solution
The solution to the problem lies in the Rswag spec file highlighted above. Rswag populates the metadata[:operation]
hash with OpenAPI parameter values. I tried it, updated Redocly and voila!
path('/v1/cards') do
post('Link a card') do
tags('Payment Method')
consumes('application/json')
produces('application/json')
security([bearerAuth: []])
operationId('linkCard')
description('Links a card to an existing customer.')
# custom OpenAPI configuration under `metadata[:operation]` hash
metadata[:operation][:servers] = [{ url: 'https://cards.example.com', description: 'PCI compliant secure card portal' }]
# rest of the tests code here...
end
end
Conclusion
Rswag has limited coverage of the OpenAPI specification. Still, the good news is that we can easily directly manipulate the metadata or even introduce our helpers to get the job done. While my issue was with the servers
attribute, you should be able to use it with any other.
Happy hacking!
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.