Using Tags in your OpenAPI Spec

Working with OpenAPI is bringing so many possibilities to the way that developers work with APIs, it’s exciting! The spec is very comprehensive though and I’ve found myself answering questions on individual aspects of it recently, so I thought I’d capture one or two of those things here. Today: tags.

Tags in OpenAPI are optional but very useful! If you use Speccy then it has Opinions(TM) and will suggest that you need tags on every endpoint. The formal definition doesn’t require it however and I tend to turn off these rules for small APIs.

When tags really come into their own is on larger APIs, perhaps an application only has one API and everything goes there – or there is one “utility” API that’s a catchall for anything not important or big enough to need its own API. Using tags on these larger APIs can really help users to find their way around.

Adding Tags to an OpenAPI Spec

To add a tag to your OpenAPI spec, you need to do two things:

  1. Define the tags in a top-level tags element
  2. Add a tag to each operation in the spec

The tags element looks something like this:

tags:
  - name: Account
    description: Relating to an account (the user must have access to the account)
  - name: User
    description: Manage a user account (either your own, or one you have permissions to access)
  - name: Admin
    description: Only available to superusers

I’d recommend adding descriptions here, it helps to make it clearer both to developers and to future maintainers of the API and its description what the tag was intended for.

Then to add the tag to a path, the tags array goes at the same level as operationID, like this (remember you can add as many tags as make sense):

  /accounts/{api_key}/secrets:
    get:
      summary: Retrieve API Secrets
      operationId: retrieveAPISecrets
      tags:
        - Account

Quite a few of the documentation tools (including ReDoc which is my personal favourite) will render the endpoints grouped by tag which is very valuable. Speccy recommends having the tags alphabetically but I tend to turn this rule off where alphabetical doesn’t make sense (for example above where I have a few endpoints tagged “Admin” but most users can’t access those so I have it last in the list).

Using tags can be a valuable addition to your OpenAPI spec so I hope that sharing this example is helpful!

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.