Time for another quick post 🙂.
This time, let’s take a quick look at OpenAPI extensions (which I discovered were a thing last week 😛) and how to add them to our API description using ASP.NET Core and Swashbuckle.
What are OpenAPI extensions
OpenAPI extensions are what you’re maybe already inferring from the name, a way to extend an API description, with custom properties, to be able to describe things that aren’t supported by the OpenAPI specification.
These custom properties names need to be prefixed with
x-your-property), but only at the root level, i.e. if this property is an object, the object’s properties don’t need the prefix.
As I mentioned earlier, I just discovered OpenAPI extensions was a thing, as I never really studied the OpenAPI specification in depth, have been learning as I need things, and I had never needed this before.
When setting things up, noticed there was a need to add a
x-google-backend property to the API description.
The following, is an example from Google’s documentation.
My first reaction was… WTF is this?! 🤣
Having never noticed this before, thought this was Google coming up with things because of reasons, and my first thought was just edit the downloaded Swashbuckle generated description and add the thing there ad-hoc.
Of course, this isn’t a great to do things, so I started looking into ways to add custom stuff using Swashbuckle. Mind you, given I didn’t know about OpenAPI extensions, also didn’t know the right terms to use in the search, but at some point, after scouring a bunch of blog posts and Stack Overflow entries, found out what was the name of what I needed, so from then on, things got easier 🙂.
Making it work with Swashbuckle
So, how do we do this with Swashbuckle? Not too difficult really (after you know what you’re looking for, of course 😛).
To add this
x-google-backend property, we can create a document filter (class implementing
IDocumentFilter) and add an extension to the API description document.
Then, if we look at the generated document, we can see it there (side note, this is based on ASP.NET Core’s web template).
OpenAPI extensions are not supported only at document level, so we could add them in other places as well, like operations or schemas.
A non-sensical example could be the following:
Which would result in the following document:
As I said in the beginning, quick post, so it’s done! 🙂
We took a quick look at what are OpenAPI extensions, one example of how they can be used to include extra information about an API that isn’t part of the spec, as well as how to work with them using ASP.NET Core and Swashbuckle.
Links in the post:
- Sample implementation
- Swagger docs - OpenAPI extensions
- Google Cloud - API Gateway
- Google Cloud - Cloud Run
- Google Cloud - Getting started with API Gateway and Cloud Run
Thanks for stopping by, cyaz! 👋