How to present a read-only property in REST Api

if you have a REST API hypermedia-driven (HATEOAS), you can easily change client behavior by enabling or disabling links in the response ( _links ). This allows the client to completely forget about the testing permissions for operations that are possible in the current state of the resource (the link to the operation is present or not).

In addition, you can leave properties in the response if the current user does not have permission to view it.

Thus, authorization is performed entirely on the server (and controls the actions and properties that can be performed / viewed).

But what if I want to have a read-only property? It is not a problem for the REST API ignore a property if it is present in the request ( _POST_ OR _PUT_ ). he just will not be saved. But how can a client distinguish between read and write properties to represent custom controls (for example, a disabled HTML input field)?

The goal is to never have client request user permissions, but to have a fully managed resource client/frontend .

Any help is appreciated :-)

+6
source share
1 answer

If I misunderstood your question, I apologize in advance. With that said ...

But how can the client distinguish between records and read-only properties to present the user with the appropriate controls (for example, the HTML input field is disabled)

Well, there are several solutions. The simplest one I can think of is to make each property an object that has a simple structure of something like:

  ... someProperty: { value: 'some value', access: 'read-only' }, someOtherProperty: { value: 'some value', access: 'write' } ... 

Obviously, you can do as creatively as you do with the way you represent the level of access to it (using enumerations, Booleans, changing access as isReadOnly or something else).

After that, the person using the API now knows that it is read-only or not. If they pass the β€œwrite” value for the read-only property as part of the POST payload, then they should expect nothing but a 403 response.

Edit: If you cannot change the properties this way, there are a number of other ways that you can still achieve this:

  • write documentation that explains how each property has access
  • create a route along which the user can send 1 or more properties to receive a response that indicates the access level of each property (response: {propName: 'read-only', propName2: 'write', etc.)
  • Returns an Access property map as part of the response (mapping properties for accessing levels).

end of the day, you just need a way to map the property to the access level. however, it depends on what your limitations and requirements are for the api, what changes you can make, and what is acceptable for both your client (s) and business requirements.

0
source

All Articles