I'm a big fan of writing an OpenAPI specification for my APIs, even internal ones. But how do you document what permissions are needed for each endpoint?
My answer depends on whether the API is intended to be used by external parties or if it's only for internal use.
For an internal API, my preference is to not include permissions in the specification directly. The team should already have a shared set of requirements for the application, and permissions are an important part of those requirements.
This doesn't diminish the value of an API spec. The specification is great for details like field types and validation logic, things that probably aren't spelled out in very technical terms in the requirements. But for permissions, I think it makes the most sense to communicate those as part of the requirements.
Of course, if you're working in a massive organization or where there are silos between teams, my reasoning might not apply.
Now let's talk about an API meant for a public audience. Here, it is absolutely critical to document permissions in the API specification.
OpenAPI has the concept of scopes, but they only apply if you're using OAuth 2, which I typically don't use on my Laravel APIs. So how can we document permissions in a way that's useful for external developers?
I like to create a Schema
object for each permission, and I use the same permission values as defined in my Laravel app:
components:
schemas:
PermissionCompanyCreate:
type: string
value: company-create
Then, on each endpoint, I define my own custom property as an array of these permissions, using the schema reference:
paths:
/companies:
post:
summary: Create a company
x-permissions:
- $ref: '#/components/schemas/PermissionCompanyCreate'
And finally, I make sure that my API includes the list of permissions this user has when they authenticate. Now, the person building against my API has all the information they need to understand how we enforce permissions and build the best experience for their user.
Here to help,
Joel
P.S. Would you like some help building or improving your API? We can help!