We are trying to implement a REST API for an application we have now. We want to expose read/write capabilities for various resources using the REST API. How do we implement the "form" part of this? I get how to expose "read" of our data by creating RESTful URLs that essentially function as method calls and return the data:
GET /restapi/myobject?param=object-id-maybe
...and an XML document representing some data structure is returned. Fine.
But, normally, in a web application, an "edit" would involve two requests: one to load the current version of the resources and populate the form with that data, and one to post the modified data back.
But I don't get how you would do the same thing with HTTP methods that REST is sort of mapped to. It's a PUT, right? Can someone explain this?
(Additional consideration: The UI would be primarily done with AJAX)
--
Update: That definitely helps. But, I am still a bit confused about the server side? Obviously, I am not simply dealing with files here. On the server, the code that answers the requests should be filtering the request method to determine what to do with it? Is that the "switch" between reads and writes?
There are many different alternatives you can use. A good solution is provided at the microformats wiki and has also been referenced by the RESTful JSON crew. As close as you can get to a standard, really.
Operate on a Record
GET /people/1
return the first record
DELETE /people/1
destroy the first record
POST /people/1?_method=DELETE
alias for DELETE, to compensate for browser limitations
GET /people/1/edit
return a form to edit the first record
PUT /people/1
submit fields for updating the first record
POST /people/1?_method=PUT
alias for PUT, to compensate for browser limitations
I think you need to separate data services from web UI. When providing data services, a RESTful system is entirely appropriate, including the use of verbs that browsers can't support (like PUT and DELETE).
When describing a UI, I think most people confuse "RESTful" with "nice, predictable URLs". I wouldn't be all that worried about a purely RESTful URL syntax when you're describing web UI.
If you're submitting the data via plain HTML, you're restricted to doing a POST based form. The URI that the POST request is sent to should not be the URI for the resource being modified. You should either POST to a collection resource that ADDs a newly created resource each time (with the URI for the new resource in the Location header and a 202 status code) or POST to an updater resource that updates a resource with a supplied URI in the request's content (or custom header).
If you're using an XmlHttpRequest object, you can set the method to PUT and submit the data to the resource's URI. This can also work with empty forms if the server supplies a valid URI for the yet-nonexistent resource. The first PUT would create the resource (returning 202). Subsequent PUTs will either do nothing if it's the same data or modify the existing resource (in either case a 200 is returned unless an error occurs).
The load should just be a normal GET request, and the saving of new data should be a POST to the URL which currently has the data...
For example, load the current data from http://www.example.com/record/matt-s-example and then, change the data, and POST back to the same URL with the new data.
A PUT request could be used when creating a new record (i.e. PUT the data at a URL which doesn't currently exist), but in practice just POSTing is probably a better approach to get started with.
Related
I've been learning how to build an ASP.NET Core Web API using the official documentation. However, under the PUT section it says:
According to the HTTP specification, a PUT request requires the client to send the entire updated entity, not just the changes. To support partial updates, use HTTP PATCH.
I know that POST is used to create a new resource and PUT is used to update a particular resource. But I cannot understand what is meant by "entire updated entity, not just the changes".
I cannot understand what is meant by "entire updated entity, not just the changes".
You should review the HTTP specification, which describes the semantics of PUT.
A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response.
Representation here refers to the bytes that would appear as the payload of the GET request. For a web page, we're talking about the HTML. For a resouce that responds with application/json, we're talking about the entire json document.
In other words, if you want to create/edit a json document, and save it on the web server, then you use HTTP PUT, and the payload of the request should be the entire JSON document.
For cases where the JSON document is very big (much bigger than the HTTP headers) and the changes you are making are small, then you might instead choose to send the changes in a patch request, where the payload of the request is a patch document (probably JSON Patch or JSON Merge Patch
Now, here's the magic trick -- everybody on the web understands HTTP requests the same way. PUT always means PUT, PATCH always means PATCH. So you can use PUT and PATCH to make changes to things on the web that aren't really documents, but might instead be something else (like an entity).
That's pretty much the point of an HTTP API - it's a facade that (when seen from the outside) makes our service look like just another web server.
The fact that your resource is really rows in a database instead of a document on a file system is an implementation detail that is hidden behind the Web API.
Supposed you have a json Data like below
{
"Id":123,
"FirstName":"John",
"MiddleName":"Random",
"LastName":"Doe"
}
Suppose, you want to change middle name here. you want to remove it. You can use both put and patch to do so.
PUT
Here you've to send the whole new entity (the changed state of the json model) in your request. Though you're only changing the Middle name part, the full json data is being sent in the request payload
PUT /user?id=123
{
"Id":123,
"FirstName":"John",
"MiddleName":"", //Only this is being changed.
"LastName":"Doe"
}
PATCH
In this case, you can only send the diff between the old model and the new model, and that will be it. So, here, in this case, only the changes are being sent, not the whole updated entity
PATCH /user?id=123
{
"MiddleName":"", //Only this is being changed.
}
Using PATCH can be handy when you want to edit only a few properties of a huge object.
I'm writing a stateless API. You send it a document, it processes the document, and then returns the processed document. I'm struggling to understand how the RESTFUL rules apply. I'm not retrieving data, creating data or updating data on the server. There is no data on the server. What do I need to use in this case as the http method and why?
Good news - you are right that it is confusing.
Nothing on the server changes in response to the request. That suggests that the request is safe. So GET is the natural choice here... BUT -- GET doesn't support message payloads
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
HEAD, the other ubiquitous safe method, has the same problem (and is unsuitable when you want to return a document in any case).
The straight forward thing to do at this point is just use POST. It's important to realize that POST doesn't promise that a request is unsafe, only that it doesn't promise that it is safe -- generic components won't know that the request is safe, and won't be able to take advantage of that.
Another possibility is to look through the method registry, to see if somebody has already specified a method that has the semantics that you want. Candidates include SEARCH and REPORT, from the WebDAV specifications. My read of those specifications is that they don't actually have the right semantics for your case.
A Lot of ways to do what you want. But here is a small guideline.
I would create an endpoint that receives the document:
/receive_document
with a 'POST' method. Since you are 'sending' your document to the server
I would create an endpoint that serves up the processed document:
/processed_document
with a 'GET' method. Since you want to retrieve / see your document from the server?
The problem that you are trying to solve is mainly related to the document size, and processing time before returning the response.
Theorically, in order to use a restful approach, you have an endpoint, like yourhost.com/api/document-manager (it can be a php script, or whatever you are using as backend).
OK, so instead of naming the endpoint differently for each operation type, you just change the HTTP method, I'll try to make an example:
POST: used to upload the document, returns 200 OK when the upload is completed.
GET: returns the processed document, you can also return a different HTTP code, in case the document is not ready or even different if the document hasn't been uploaded. 204 no content or 412 precondition failed can be good candidates in case of unavailable document. I'm not sure about the 412, seems like it's returned when you pass a header in the request, that tells the server which resource to return. In your case, I think that the user processes one document at time. But to make a more solid api, maybe you can return an ID token to the user, into the POST response, then forward that token to the GET request, so the server will be able to know exactly which file the user is requesting.
PUT: this method should be used when updating a resource that has been already created with POST
DELETE: removes a resource, then return 204 or 404
OPTIONS: the response contains the allowed methods on this endpoint. You can use it to know for example which privileges has the currently logged user on a resource.
HEAD: is the same as a GET call, but it shouldn't return the response body. This is another good candidate for you to know when the document has been processed. You can upload with POST, then when the upload is done, start some kind of polling to the same endpoint with the HEAD method, finally when it will return "found", the polling will stop, and make the final GET call, which will start the download of the processed document.
HTTP methods are a neat way of managing HTTP communications, if used properly are the way to go, and easily understandable by other developers. And not to forget, you don't have to invent lots of different names for your endpoints, one is enough.
Hope that this helped you a little... But there are loads of guides on the net.
Bye!
Given a one page app that uses push state and RESTful backend, we can imagine accessing the listing of a resource at /resourceName (i.e. /users). So /users would create a formated list of users
Now the problem is that this resource JSON or XML feed should also be mapped to /resourceName, so if boot form my application entry point at / then all is good, when navigating to /users the JS router can trigger a Ajax call that get the JSON data. Now the problem is if the URL is pointing directly at /users then i will land on a JSON feed instead of the actual listing. I could route all call to a main entry point and then let the JS router do the work though if i do so the AJAX call to fetch JSON wil brake.
I remember a while ago people adding .json to their json request, or even a GET parameter ?format=json and then having the controller taking different actions. I find that somewhat hacky.. Are there any other ways to go about this?
For that matter i am using laravel4 backend and backboneJS
I think the .json on the end of the request is the best approach. the other approach could be to create a separate endpoint endpoint for api request api.mydomain.com vs www.mydomain.com
What method you use to get a different response depends on how you'd like to go about it. Since you're asking about an opinionated topic (There is no one right answer), here's some options you can explore.
First, here's a good read from Apigee on API design, which covers what I'll write about here. See page 20 on "Support multiple formats"
The Rails way: Append a .json, .xml or other extension at the end of your request and handle that code within Laravel (You may want to use the "before" filter to check the request or Laravel's excellent route parameters, which allow the use of regex to define the route).
You can check the "accept" header in the request and set that header in your ajax calls to "application/json" instead of the default "application/html" to inform your application which format to use in its response. Again, the before or after filters may come in handy to check the request and define the response as appropriate
Create a query string `?format=json" or similar. Same comments as in point 1.
Laravel doesn't have built-in methods to change the response for you. You can, however, fairly easily detect what's being asked and choose which format to return in. It does take some thinking about how you want to accomplish that, however.
Some options off the top of my head:
Use the "before" or "after" filter to check what the request "wants" for a format, and do some transformations on the response to make that work
Extend the request and response class to "automate" this (request class to detect format, response class to transform the response to the correct format)
Hope that helps
It's valid to say which representation do you want. E.g. JSON, XML or binary, depends on what you want and which serializers have you developed.
You framework should support either setting of default representation or if you provide some mapping URL -> method you should be able to say which representation you are going to return - also either by default or taken within some object which represents your request.
I ended up using different endpoints as suggested by #Aaron Saunders. In laravel 4 this is dumb easy to implement using group routes:
app.php:
'domain' => 'whatever.dev',
routes.php:
define('APP_DOMAIN', 'app.' . Config::get('app.domain'));
define('API_DOMAIN', 'api.' . Config::get('app.domain'));
Route::group(array('domain' => API_DOMAIN), function()
{
// API ROUTES
});
Route::group(array('domain' => APP_DOMAIN), function()
{
// VIEW ROUTES
});
Beautiful!
Thinking in a RESTful way, is it correct to use POST to create in a single call a resource and its sub-resource?
In my application I have the resource /notices/{notice} and sub-resource /notices/{notice}/photos/{photo}. A {photo} can't exists without a {notice}, but a {notice} doesn't have necessarily photos. Normally, I have to do first a POST to create a notice, then another POST to add a photo.
Now I want to allow the creation of a notice with a photo directly attached, enabling the creation of /notices/{notice} and /notices/{notice}/photos/{photo} with a single POST request to /notices/{notice}/photos/{photo}, with a multipart content describing both the resources (JSON for notice, binary for the photo). I think I will return the Location header only for the sub-resource.
Essentially, I want this to prevent Android clients to send two POST request to the server to upload a notice with a photo.
Is this correct? Or does it infringe REST principles? Should I consider to keep them separate and make two different requests? Or is it wrong to consider photos a separate entity from the notice? Should I keep only /notices/{notice} as resource, using PUT to add photos?
Which is the best solution?
Yes, there is nothing wrong with creating sub-resources at the same time you create the parent resource. It would even be OK to use PUT instead of POST to do this, as everything under the parent URL is part of/belongs to the resource you are uploading.
EDIT:
Now I want to allow the creation of a notice with a photo directly attached, enabling the creation of /notices/{notice} and /notices/{notice}/photos/{photo} with a single POST request to /notices/{notice}/photos/{photo}
This I disagree with. I suggest POSTing to the collection resource's URL, /notices. You provide the notice and its photos as a single representation (request body). The back end will then create resources for both the notice and any constituent photographs.
Although its essential in many cases, multiple edits/creates are not formally addressed by the RESTful architecture style.
Problem starts when you need to report failures on part of the collection, and the problem is worsen when they failures have different cause.
An it will effect choosing the right Hypermedia controls which are essential for the client to find a way forward in the given transaction/conversation.
so my suggestion is to have a nested cycle or POST requests rather than a sing POST to create nested Resources , so that it'd be easier and clearer to address each Resource state change.
Pardon the simple question, but it seems most searches try to tell me which methods are designed for what actions. Eg, create & edit is PUT, create from plural (articles) is POST, and so on. (If you disagree with this, i was just using it as an example. :)
With that said, how do you initiate a resource edit? To create a resource, with a known url you preform a GET on an non-existing URL. Eg, GET:mysite/resource_one. This then returns a form, and the form submits a PUT to the same address and bam, the resource is created.
Now how do you edit that same resource? With 4 Methods, designed for CRUD, i am having issues because i can only seem to think of one way. To go to a new resource. Eg, GET:mysite/resource_one/edit. This then presents a form with existing data, you edit it, and then the data is submitted to GET:mysite/resource_one. This seems odd to me in a system that seems to be designed to allow full CRUD to be preformed on a resource, without leaving said resource.
So.. what is the proper method? I mean, if GET:mysite/resource_one/edit is right, then why not GET:mysite/resource_one/delete, GET:mysite/resource_two/create, and so on..
Replies much appreciated!
The URL always represents the resource, not the action. Thus, while mysite/resource_one/edit might be a proper URL to a page that initiates editing a resource, it's not a part of the REST API itself, it's part of the web app that uses that REST API to manipulate that resource. Moreover, in that example mysite/resource_one would be a confusing representation of the resource.
To create a new resource, you use POST on the parent resource, with the body of the request containing the data for the new resource. The response contains the URL for the newly created resource.
To update an existing resource, you use PUT on the resource URL, with the body of the request containing either full or partial update of the resource data.