Saravanan M
Saravanan M

Reputation: 4747

How to define a boolean API RESTful?

I have to define an API that answers whether a resource with given ID can be created, like

Can I (caller) create this resource with id=resource1 ?

The possible responses could be

Now my questions are

  1. How can I model the API? Will, GET /resources/resource1 be a good choice?

  2. What HTTP codes will suite for responses like, (a) this resource id is already taken, (b) you don't have permission to create this particular id (but only few other ids), (c) you can create this id.

Upvotes: 6

Views: 10509

Answers (3)

Thierry Templier
Thierry Templier

Reputation: 202276

Since you want to check the permissions regarding the addition, you should use a different resource than the one that actually added the element. IMO something like /permissions/{elementName}?id=theid or /permissions/{elementName}/{operationName}?id=theid. Accessing it with method GET would suit.

Using the same resource would be a bit "messy" I think since I would expect the method GET on /resources/resource1 to actually return the content of the element with identifier ressource1.

Regarding the response, I would see this:

  • 401 if the user isn't authentication and the permission resource requires an authentication.
  • 204 if the current user is allowed to add an element with the specified identifier. I don't think that you need a response payload in this case.
  • Regarding the case when the user isn't allowed to add an element with the provided identifier, I think the status code 403 (Forbidden) suits. Perhaps a status code 400 could also match if you consider that the user provides a wrong content. In this case some hints about the error (identifier value not allowed) should be returned within the response payload.

For me, the status code 409 (Conflict) is more when implementing optimistic locking, i.e. concurrent accesses (updates) on the same element.

Hope it will help you, Thierry

Upvotes: 1

Charles0429
Charles0429

Reputation: 1420

An example in github may help you.

The api designed for checking if a user is following another user:

GET /user/following/:username

The deal information is presented in github's api document

For your question1, I think you can implement like this:

GET /resource/existence/:resource_id

For question2, you may also take a look at github's client errors

Upvotes: 6

Matthew Smith
Matthew Smith

Reputation: 56

Would it be better to just try and create the resource with a POST? and let your implementation handle the response from there? In which case your responses could be:

a) 409: Conflict
b) 401: Unauthorized
c) 200: OK

If that's not possible, then I guess your payload response from a GET can contain the result. Something as simple as:

true: You can create the resource
false: You cannot create the resource

Upvotes: 1

Related Questions