REST application POST and redirect - php

usually after POST request need to be done redirect to new url (at least it's a right proactice to build obvious web applications).
What to do with RESTfull app after POST is received and completed ? Should I send to client 302 Header with new url ?
And another question related with REST approach: what about pagination, ordering and filtering the generic GRID ? I'm talking about usual javascript grids which has such functions like searching, sorting, filtering and paginating how it is applicable with REST approach (it is GET ?) ?

There is actually a dedicated status code to return after a resource-creating POST request: 201 Created. It is accompanied by a Location HTTP header which points to the newly reported response.
As to pagination, the usual approach is to define the subset of the data you want to retrieve with GET query parameters. For instance, to retrieve the first 50 entries of an employee list, the request could look like this:
GET /employees?entries=50
And the next 50 like so:
GET /employees?start=50&entries=50
and so on.

Related

Should GET requests store to database?

I’ve read that you should not use GET requests if you are modifying the database. How would you record analytics about your website then?
For example, I want to record page views whenever someone visits a page. I would need to update views = views + 1 in the database. Is this OK, despite using a GET request, or is there another technique? Surely, not every request should be a POST request.
The general advice about how to use POST vs. GET shows up in RFC 1945 from 23 years ago:
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.
 
POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Providing a block of data, such as the result of submitting a form [3], to a data-handling process;
Extending a database through an append operation.
These guidelines remain in effect to this day, but they cover the primary purpose of the user's page request.
The act of incrementing a view counter is incidental to the primary purpose of the request, which is to view the page content. Indeed, the user is likely unaware that this database update is occurring.
(Of course, you must expect that you will receive duplicate requests as users move through browser history, caches are populated, or spiders crawl your pages. This wouldn't be the case if a POST request was made.)
It's ok.
When you make POST request, you actually wait for POST params to come and you build your database insert query based on parameters which you've got from browser.
On GET request you actually implement your own business logic, so user won't ever know what is going on the side.
And for the finish, actually sometimes you can do something, what's going against rules, rules are good, but we are able not to follow them, that's what makes us human, if we would strictly follow all the rules, it would be cumbersome.

Ionic App POST/PUT/DELETE/GET method(s) response capture and display

I am a beginner and learning for example to submit a form to create an order (using POST method), edit an order (using PUT method), delete an order (using DELETE method) or search for an order (using GET method) targeting a restful web service. The order info is captured by the server script (probably PHP) and depending on the http method the order is either inserted, updated or deleted respectively. I have no knowledge of how the script does it.
My 2 questions are:
when I POST, PUT or DELETE, the server script could successfully perform the operation on the database (or) be unsuccessful in making changes to the database. How will I know if the script performed the database operation successfully or failed or there was some other error so that I can display a status to the user of the app accordingly?
(I understand that for a GET request the script sends the data requested in JSON or XML and I need to parse the JSON and display it to the app user. I just dont understand how it works for POST, PUT or DELETE. Will I receive a json for info or should I look somewhere else to able to provide a useful response to the app user).
I see POST being used instead of GET to get JSON response. My understanding is that POST is for insert operation only. Am I missing something? Why POST is being used in real time sometimes.
Thank you for your time in advance!
When the script finishes you send back a status code (200 is okay, 500-Internal server error, 404-Not found etc) and a message (json in your case)
"I see POST being used instead of GET to get JSON response", depends on what type of processing you are referring to. If you need a resource (a specific entity) you make a GET request, but if you need to make a custom process or a search then POST might be good for you
P.S: A good read on implementing a API an here. Check out the status codes used in the example, you can change your implementation based on your needs

What's the best approach for deleting the record: Laravel 5.2.15

I am using Laravel 5.2.15.
There are list of records in a webpage with Edit and Delete button with each record. I have two approaches for deleting the record
Use JQuery and send Ajax Request to server.
Place a form tag for delete button in each row.
I have following question
In case I use Approach 1, can it cause any issue when the site will be viewed from Android or iPhone? I have another option to do Server side validation using Request class.
In case of Approach 2, Will it make the page heavy? I am using Pagination, so 10 records will be displaced per page.
Please guide me if I should go with which approach or please suggest if both approaches are incorrect.
The questions you have don't really focus on the main reasons to choose one above the other. They differ mostly in how the request is sent to the server and how the page is refreshed to show the results.
Using Ajax is a very common approach and relies on using Javascript, a technology that has been available in all browsers for a very long time. Compatibility will not be a problem as most of the internet wouldn't function without it anyways (and you can even make it work using your second approach as a fallback mechanism). The request you sent is typically a HTTP DELETE request to a REST endpoint so that the server then knows to delete the record1. Upon receiving the success response from the server the page is responsible for updating itself by removing the row corresponding with the just deleted record, and possibly fetching new records to still have 10 rows on that page. No page refreshes required, but some Javascript required.
Your second approach is kind of old school in that the form you submit contains some kind of identifier such that the server knows what to do. This is a full page load and should be a HTTP POST request if you want to do it properly2. Following the Post/Redirect/Get idiom the server then sends a Redirect response so that the browser will then trigger yet another normal page load as GET request to show the user the updated list of records. You do not have to update the page manually by yourself, at the cost of having annoying page reloads (this isn't really expected anymore in the current day and age).
My advise would be to go with the first approach. It is the modern way of doing things and allows for having non-reloading pages. It does however require some additional work on the client side (in Javascript) to update the page accordingly.
As a side note, CSRF must be taken care of in both instances really. Always include a CSRF token with every 'update' action you perform on the server.
1 You have to program this yourself, of course :)
2 Browsers don't generally support anything other than GET and POST, although the HTTP specification allows for much more request methods.
It depends upon your requirements. But you should go with the 1st approch. If you will use 2nd approch the you will have to refresh the page since you can not handle the response. So basically if you delete 5 items the page needs to be refreshed 5 times and you may not send more than 1 delete request at a time. Now If you use 1st approch since It's ajax and javascript you can display appropriate message depending upon the result and no need of unnecessary page refresh.Plus as you mentioned you can do validaton using Request class. So you can handle bad or malicious request. And I am sure CSRF won't be that much of a problem since you can check whether the request is ajax or not using Request::ajax(). So 1st approch is better mostly because of that no page refresh.
Both approaches are fine ;)
But 2nd approach would be better than first one; Using this approach you can prevent CSRF attacks too;
I would suggest you to use method 1 with certain modifications.
Use get request to delete the record.
Send a CSRF token and dont forget to encrypt your id for the record
add your delete URL to href
Then when you do ajax request, use the url from href and you could send some additional parameter like is_ajax=1, but laravel already checks for the jquery header so Request::isAjax() method will let you know if the request was an ajax request or normal request.
Now all you need to do is send different response for ajax and normal request.
HOPE THIS HELPS :D
Another drawback of your second approach which haven't been mentioned is displaying validation errors. Specifically from your edit and even your delete actions.
If you have multiple forms for each set of data showing errors from validation would be a pain. But if you follow approach number 2 just by getting the reference of the row element submitted, you could easily append an alert div if ever an error from validation has occurred.
as for the delete action, somebody else might have already delete some shared data so you might also want to tell the user somebody already threw this out.

Losing Session when get request header is too long

I'm having a problem with my application.
I created a filter panel on which the users can select multiple parameters and then I pass them to a GET request that hits a function inside a controller that returns the results. All this is very basic stuff, I had no problem implementing this. But my application uses uuids and the request URI gets very long. That results to losing my current session, log out current user and Laravel to generate a new session token.
The URI is something like this:
www.domain.com/search?offer_category[]=892b06ac-6552-43ca-9fcd-ba65d4223e7d&offer_category[]=bc66fd8d-1ea9-4968-bee5-8ab9ab665446&offer_category[]=46907770-13d8-4ba1-be33-58f254624860&offer_category[]=6fd45d2b-8dc0-4d8e-a94c-1d3eab86eb0a&offer_type[]=62f23e8b-c22e-43f7-8bf6-8b393e81a1ca&offer_type[]=d33b2a38-50fe-4868-8cfc-9af9ef39d91e&order_by=duration_to&order_dir=asc
Why is this happening? Is there a max header character count for GET request? Can I get through this? I don't want to use a POST request, I don't think it's the right way to do a search.

Creating custom status codes

I'm having an API on which I need to set custom status code. Apart from the normal standard http status codes, is it the best practice to create our own status code?
i.e, If my client is sending a blank parameter (orderID), can I set a random status code number of my own say 123? Or is there any standard way to create customer status codes?
There are quite a lot of existing codes, so usually you won't need to invent new ones. You might, though, but when you do, make sure to use the right ranges.
For instance, the 200+ range indicates success of any kind, 300+ is a redirect, 400+ range is a client error (bad url format, target not found), and 500+ is a server error.
By following these guidelines, you can use all kinds of clients to communicate to your api. A browser should normally display the results of any 2XX status code, and treat it as a succesful request, even if the particular XX is unknown to it.
For a rather complete list of status codes and their normal meaning, as well as a general description of each of the ranges, see this:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
599 is the highest assigned status code. I wouldn't know if it's allowed to use the 600+ range, but I cannot find anything about it. I cannot imagine that your status wouldn't fit in any of the existing categories, though.
REST:
Aside from the return code, you can (should?) also have a look at the different methods. You probably know GET (sending data in url) and POST (sending extra data with the request), because they are commonly used. But you also got PUT and DELETE, which are especially useful for an api like this. If you search for terms like Restfull API, you should get plenty of documentation about this subject. Also, see this W3 link for an overview of request methods.
Bringing it together:
For creating a customer through the api, you could send a PUT request with the data of the new customer. The api can return 201 Created with an ID (or slug) for the customer. If you want to delete the customer, send a DELETE request and return 204 No content, since you just need to confirm that the delete succeeded, without sending any content.
Or is there any standard way to create customer status codes?
No. I'd go for a generic HTTP error as 400 Bad Request and provide a meaningful error message in the response body. This wasy you don't have to make up HTTP codes as you go, and your consumers can process different error responses identically.
Don't define custom status codes unless you're willing to going through the process of standardizing them (http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-26.html#considerations.for.new.status.codes).
Otherwise just use a generic one and send additional details in the response body.

Categories