Is GET /entry/new considered best practice for displaying the input form for creating a new resource? - rest

Consider a Resource named Entry, with endpoints:
GET /entries (show all entries)
GET /entries/<x> (show entry x)
POST /entries (create new entry)
PUT /entries/<x> (change an existing entry x)
DELETE /entries/<x> (delete an existing entry x)
These I'm sure of. But how about:
GET /entries/new (show input form for creation of new entry)
GET /entries/<x>/edit (show input form for update of existing entry)
Are these patterns considered best practice as well? If not, which are?

GET /entries (show all entries)
GET /entries/<x> (show entry x)
POST /entries (create new entry)
PUT /entries/<x> (change an existing entry x)
DELETE /entries/<x> (delete an existing entry x)
Are all OK, as you expected.
GET /entries/new (show input form for creation of new entry)
GET /entries/<x>/edit (show input form for update of existing entry)
If you want to keep it simple, these two are OK as well (they are common, used by big players and frameworks, respect RESTful principles and are somewhat of a standard).
Sources/samples:
Microformats wiki - some good info here, with suggestions on how to work around browser method limitations
Stack Exchange: /questions/ask (instead of /new) to display the create form; /questions/id/slugified-title to view; /post/<x>/edit to display the edit form.
GitHub's issues: /project/issues; /project/issues/new; /project/issues/<x>; they don't have an /edit URL, as all editing is done in-place via JS.
The standard followed by Rails: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
Long story
To achieve the scalability and loose coupling of a go RESTful architecture, it helps to think of your application in terms of resources. So every URL should be pointing to a different resource. So:
GET /entries/<x> is OK because it would return the resource "entry of identity <x>".
Now, the GET /entries/new is a resource as well, but more of a "utility" one. It is just that the resource presented by this address is a form (a document explaining how to create entries - could be a WADL instead of a form as well).
The /edit possibilities
The GET /entries/<x>/edit, if you want, is the one we could get by without. As we know, the GET returns a representation of the current state of a resource, not (necessarily) the resource. This way, if a resource is (currently) editable, the GET URL would return it in an editable fashion, if not, then it would be read-only (thus no need for an /edit resource).
Another way of achieving this is having GET entries/<x> return JSON of HTML content based on the Accept header. This way, if the Accept had text/html, the page returned would be a form containing the all the info (again, if the resource was in an editable state, the form would be editable. If not, then it would be read-only).
Now I see this may not be optimal, as you may not want to display the form everytime (on GET /entries/<x>). If this is the case, you have almost two resources:
GET /entries/<x> - the entry
GET /entries/<x>/edit - This "resource" would be a file describing what sort of HTTP request the client must make if it wants to edit an entry state. In your case it is a form (telling the client how to send or simulate a PUT request), but could be a short WADL file as well.

Related

RESTfully change operation behaviour

The Situation:
Via POST operation, users can create a new resource based on given parameters. If there already exists a resource created from these same parameters, the existing resource is returned instead.
Users are able to GET this resource if they know the resource ID (generated on creation, and is effectively random). I would like to provide users a way to check existence only knowing the creation parameters and without creating a new resource.
The Question:
Would it be RESTful to take some kind of "just-checking" property in the POST body to prevent a new resource from being created?
An Example:
POST vehicle
{
colour: 'red',
wheels: 4
}
201: {
vehicleId: '314-159',
colour: 'red',
wheels: 4
}
GET vehicle/314-159
200: {
vehicleId: '314-159',
colour: 'red',
wheels: 4
}
POST vehicle
{
colour: 'red',
wheels: 4,
check: true
}
200: {
vehicleId: '314-159',
colour: 'red',
wheels: 4
}
POST vehicle
{
colour: 'blue',
wheels: 8,
check: true
}
404: Not Found
Edit
Much of the discussion has been around whether the POST operation should be idempotent, which, while valid, does not address my question.
I would like to provide my users with a way to validate the existence of a resource based only on the properties that would be used to create the resource.
The idempotency of the POST method is irrelevant. What suffers from the absence of this check is subsequent GET requests which will contain a number of resources that are never intended to be used, and make it more difficult to find useful information.
A POST request containing a "do-not-create" flag would fill this need, but may not feel RESTful.
How about implementing an idempotent post? In doing so you could avoid the “check” body param.
2 ideas:
Use PUT and natural keys
One option (not sure if this works for you) is to not use some database-id in the url but use something that's a bit more like a natural key.
So instead of POSTing on some collection, you just PUT the item:
PUT /vehicles/colour/blue/wheels/8
PUT can also be used for creation just fine. And you could use a header such as this to prevent overwriting existing values:
If-None-Match: *
Don't put it on the client to do this
What if a POST for creating an item is identical to updating it? Or, what if you call POST on an existing item, it just doesn't actually do anything.
Maybe the client doesn't need to know if it just created a new item, or if the server already had that item.
Just make sure that for those 2 cases the server behaves the same, and you should be good.
Users are able to GET this resource if they know the resource ID (generated on creation, and is effectively random). I would like to provide users a way to check existence only knowing the creation parameters and without creating a new resource.
How would you do it with a web site?
Probably, with a form, that would accept as inputs the same creation parameters. The user is in effect performing a search, which is a semantically safe operation, so the form would likely use the GET method and have the arguments from the form encoded into the query string.
The endpoint, on receiving that request, could redirect it to the appropriate resource (if one already exists) or to another resource to handle the case when it doesn't.
Would it be RESTful to take some kind of "just-checking" property in the POST body to prevent a new resource from being created?
Sure - again, how would you do this on a web site? The form would have an extra checkbox, set to the correct default behavior, but giving the user the option to change it before submitting the form.
Because switching the check box changes the semantics from a safe operation to an unsafe operation, you might want to change the method on the form during submission -- HTML by itself doesn't do that, but you can do it with javascript aka code on demand.
Using POST for safe operations isn't ideal, because generic components can't tell that the operation is safe. This means that they can't know to automatically retry the request if the response is lost, they don't have the correct default cache behaviors, and so on.
For the record, the solution chosen was to add options for a special case on the GET method.
As touched on in this answer, it is not quite in the spirit of the POST method to perform this type of operation, and it muddies the model being presented to the users.

Should a RESTful API avoid requiring the client to know the resource hierarchy?

Our API's entry point has a rel named "x:reports" (where x is a prefix defined in the HAL representation, by way of a curie - but that's not important right now).
There are several types of reports. Following "x:report" provides a set of these affordances, each with a rel of its own - one rel is named "x:proofofplay". There is a set of lookup values associated with this type of report (and only this type of report). The representation returned by following "x:proofofplay" has a rel to this set of values "x:artwork".
This results in the following hierarchy
reports
proofofplay
artwork
While the "x:artwork" resource is fairly small, it does take some time to fetch it (10 sec). So the client has opted to async load it at app launch.
In order to get the "x:artwork"'s href the client has to follow the links. I'm not sure whether this is a problem. It seems potentially unRESTful, as the client is depending on out-of-band knowledge of the path to this resource. If ever path to artwork changes (highly unlikely) the client will break (though the hrefs themselves can change with impunity).
To see why I'm concerned, the launch function looks like this:
launch: function () {
var me = this;
Rest.getLinksFromEntryPoint(function(links) {
Rest.getLinksFromHref(links["x:reports"].href, function(reportLinks){
Rest.getLinksFromHref(reportLinks["x:proofofplay"].href, function(popLinks){
me.loadArtworks(popLinks["x:artwork"].href);
});
});
});
}
This hard-coding of the path simultaneously makes me think "that's fine - it's based on a published resource model" and "I bet Roy Fielding will be mad at me".
Is this fine, or is there a better way for a client to safely navigate such a hierarchy?
The HAL answer to this is to embed the resources.
Depending a bit on your server-side technology, this should be good enough in your case because you need all the data to be there before the start of the application, and since you worry about doing this sequentially, you might parallelize this on the server.
Your HAL client should ideally treat things in _links and things in _embedded as the same type of thing, with the exception that in the second case, you are also per-populating the HTTP cache for the resources.
Our js-based client does something like this:
var client = new Client(bookMarkUrl);
var resource = await client
.follow('x:reports')
.follow('x:proofofplay')
.follow('x:artwork')
.get();
If any of these intermediate links are specified in _links, we'll follow the links and do GET requests on demand, but if any appeared in _embedded, the request is skipped and the local cache is used. This has the benefit that in the future we can add new things from _links to _embedded, and speeding up clients who don't have to be aware of this change. It's all seamless.
In the future we intend to switch from HAL's _embedded to use HTTP2 Push instead.

REST - Updating partial data

I am currently programming a REST service and a website that mostly uses this REST service.
Model:
public class User {
private String realname;
private String username;
private String emailAddress;
private String password;
private Role role;
..
}
View:
One form to update
realname
email address
username
Another form to update the role
And a third form to change the password
.
Focussing on the first view, which pattern would be a good practice?
PUT /user/{userId}
imho not because the form contains only partial data (not role, not password). So it cannot send a whole user object.
PATCH /user/{userId}
may be ok. Is a good way to implement it like:
1) read current user entity
2)
if(source.getRealname() != null) // Check if field was set (partial update)
dest.setRealname(source.getRealname());
.. for all available fields
3) save dest
POST /user/{userId}/generalInformation
as summary for realname, email, username
.
Thank you!
One problem with this approach is that user cannot nullify optional fields since code is not applying the value if (input is empty and value) is null.
This might be ok for password or other required entity field but for example if you have an optional Note field then the user cannot "clean" the field.
Also, if you are using a plain FORM you cannot use PATCH method, only GET or POST.
If you are using Ajax you might be interested in JSON Merge Patch (easier) and/or JavaScript Object Notation (JSON) Patch (most complete); for an overview of the problems that one can find in partial updates and in using PATCH see also this page.
A point is that a form can only send empty or filled value, while a JSON object property can have three states: value (update), null (set null) and no-property (ignore).
An implementation I used with success is ZJSONPATCH
Focussing on the first view, which pattern would be a good practice?
My suggestion starts from a simple idea: how would you do this as web pages in HTML?
You probably start from a page that offers a view of the user, with hyperlinks like "Update profile", "Update role", "Change password". Clicking on update profile would load an html form, maybe with a bunch of default values already filled in. The operator would make changes, then submit the form, which would send a message to an endpoint that knows how to decode the message body and update the model.
The first two steps are "safe" -- the operator isn't proposing any changes. In the last step, the operator is proposing a change, so safe methods would not be appropriate.
HTML, as a hypermedia format, is limited to two methods (GET, POST), so we might see the browser do something like
GET /user/:id
GET /forms/updateGeneralInformation?:id
POST /updates/generalInformation/:id
There are lots of different spellings you can use, depending on how to prefer to organize your resources. The browser doesn't care, because it's just following links.
You have that same flexibility in your API. The first trick in the kit should always be "can I solve this with a new resource?".
Ian S Robinson observed: specialization and innovation depend on an open set. If you restrict yourself to a closed vocabulary of HTTP methods, then the open set you need to innovate needs to lie elsewhere: the RESTful approach is to use an open set of resources.
Update of a profile really does sound like an operation that should be idempotent, so you'd like to use PUT if you can. Is there anything wrong with:
GET /user/:id/generalInformation
PUT /user/:id/generalInformation
It's a write, it's idempotent, it's a complete replacement of the generalInformation resource, so the HTTP spec is happy.
Yes, changing the current representation of multiple resources with a single request is valid HTTP. In fact, this is one of the approaches described by RFC 7231
Partial content updates are possible by targeting a separately identified resource with state that overlaps a portion of the larger resource
If you don't like supporting multiple views of a resource and supporting PUT on each, you can apply the same heuristic ("add more resources") by introducing a command queue to handle changes to the underlying model.
GET /user/:id/generalInformation
PUT /changeRequests/:uuid
Up to you whether you want to represent all change requests as entries in the same collection, or having specialized collections of change requests for subsets of operations. Tomato, tomahto.

How to represent a read-only property in a REST Api

if you have a REST API that is hypermedia-driven (HATEOAS) you can easily change a client's behavior by including or omitting links in the response (_links). That enables a client to completely forget about testing permissions for the operations that are possible in the current state of a resource (the link to the operation is present or not).
Additionally you can leave out properties in the response if the current user doesn't have permission to see it.
That way authorization is done entirely on the server (and controls actions and properties that are eligible to execute/view).
But what if I want to a have a read-only property? It is no problem for the REST API to ignore the property if it is present in the request (_POST_ OR _PUT_). it just won't get saved. But how can a client distinguish between write and read-only properties to present the user appropriate controls (like a disabled input field in HTML)?
The goal is to never ever have the client request a user's permissions, but to have a completely resource driven client/frontend.
Any help is greatly appreciated :-)
If I misunderstood your question, I apologize upfront. With that being said...
But how can a client distinguish between write and read-only
properties to present the user appropriate controls (like a disabled
input field in HTML)
Well, there are multiple solutions to this. The simplest one I can personally think of is to make each property an object having a simple structure of something like:
...
someProperty: {
value: 'some value',
access: 'read-only'
},
someOtherProperty: {
value: 'some value',
access: 'write'
}
...
You can obviously get as creative as you want with how you represent the "access" level of the property (using enums, booleans, changing access to be isReadOnly or whatever).
After that, the person using the API now knows they are read-only or not. If they submit a "write" value for a "read-only" property as part of the POST payload, then they should expect nothing less than a 403 response.
Edit:
In case you can't alter the properties in this manner, there are a number of other ways you can still achieve this:
write documentation that explains what access each property has
create a route that the user can submit 1 or more properties to in order to receive a response that indicates the access level of each property (response: { propName: 'read-only', propName2: 'write', etc.)
Return a propertyAccess map as part of the response (mapping properties to access levels).
end of the day, you just need a way to map a property with an access level. however that's done depends on what your restrictions and requirements are for the api, what changes you can make, and what is acceptable to both your client(s) and the business requirements.

What is the proper URI scheme for RESTful creation of a tree of nodes?

I have a ProductInstance, which has zero or more parents, also ProductInstances. They are a tree. For example:
- ProductInstance VM
- ProductInstance RAID
- ProductInstance DISK
- ProductInstance CPU
I'd like my URI-scheme to create these, to be clean and RESTful. How should I set this up?
One scheme I came up with, is to nest the URI resources:
GET http://example.com/product_instances/new - HTML form
POST http://example.com/product_instances - Create a new resource
GET http://example.com/product_instances/1/children/new - HTML form
POST http://example.com/product_instances/1/children - Create new resource who's parent is product_instance 1.
The other scheme I thought of, is to provide params and re-use the "ordinary new and create":
GET http://example.com/product_instances/new - HTML form
POST http://example.com/product_instances - Create a new resource
GET http://example.com/product_instances/new?parent=1 - HTML form
POST http://example.com/product_instances/ - include parent=1 in payload.
Are there any standards for this pattern? Is there some rule or guideline that explains how to deal with tree-ed items in RESTful URI schemes?
Note: I focus on the new and create only, because I would say that the show, update/edit and delete are no different for items with and without parents, since they act on an already stored ProductInstance and therefore the parent is known and needs not to be provided in the URI or payload.