Creating custom status codes - php

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.

Related

Notification Api System Correct Process

I built a small notification api system that has id, user_id, subject, text, status, created_at columns in the data base.
My current process is that when a user requests for her notifications i get the most recent 100 unread messages and send to the user, then wait for the front end to send me a list of ids of those that have been read by the user so that i can change their status to read.
but sometimes this does not happen meaning the when the user requests for another set of messages they will get back their already read messages.
So i am thinking of marking the messages as read once i retrieve them for the user rather than wait for update from the frontend.
but i am not sure if this is the best way to handle this! is there a better process for api notification systems please advice me. Thanks.
I would think about it like this: What is that listing of unread items depicting? What the state understands to have been left unread. Is pulling a listing of unread items really meant to denote all those items were read? I think not. You may allow a bulk mark read, but reading the list is just a stateful representation, of fact. Read the list, and authoritatively mark read when touched by a visible interface component by sending a per-item request to thing/mark-read.
If you're having issues with the (central) store not representing state accurately because you think they should be read, debug your interface. I would not mark read on pulling the list, though. That would be a flawed approach.
If you do directly insert all 100 into the display where you consider them read, create an endpoint in your api for thing/mark-items-read and pass it those 100 item ID's.
We can't see your code here, but I would suggest the following:
Store the ids of messages displayed to the use in an array on the frontend, so when a user views a message, you add the id to that array. I'm not sure what your frontend is using so can't really make a code suggestions.
Create an endpoint that receives this array on the backend in your routes file
Route::post('somepath/read-messages', 'MessageController#readMessages');
Then, in your message controller:
public function readMessages(Request $request) {
if ($request->has('read_messages') {
$messages = Message::whereIn('id', $request->read_messages)->get();
$messages->update(array('staus' => 'read');
}
}

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

Passing values through URL or POST variable instead?

I'm implementing a message system (private messaging, if you will) and I'd like to be able to display the list of messages a user has by a text link so I don't need a button to open it. The message_id (unique value in the databse) would be passed through the URL. (something like www.example.com/message/view/16).Assuming I check to make sure the session of the userid matches the userid that the message is sent to, is this OK? To make it safer I could just append a random number and set that as as session, and then just check for that upon viewing.
Should I forget this idea and just stick with a submit button to view the message?
A POST request would not provide any more safety than a GET request: any half-decent web debugging tool can forge POST requests. You should simply never trust user-input data. Always double-check authorizations for safety!
That said, GET request semantics match what you're trying to do here.
The HTTP standard says that a GET request should be repeatable without any non-trivial consequence. For instance, it's adequate to view data with a GET request (and possibly do small things like incrementing a counter, since these are pretty trivial consequences). In fact, GETand HEAD are the two request methods that are considered "safe".
On the other hand, POST requests are expected to have non-trivial consequences, like sending a message or placing an order. Stuff that you don't want to perform twice accidentally. Most browsers these days also respect this by warning users when reloading a page would cause a POST request to be performed again.
Using GET values for viewing messages is much better idea, because assuming a user stays logged in, it would allow them to bookmark messages, etc.

REST application POST and redirect

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.

Categories