Custom http codes - ajax

Could I use custom HTTP codes?
I want to use these codes as response for AJAX requests.
Example:
220 - will be correspond to status that some item was created successfully
420 - will be correspond to status that some validations errors were occurred
Each response will be has json string.

You can define extension codes, but it only makes sense if you want to standardize something; in which case you need to write a spec, and get the status code registered (see http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-12.html#rfc.section.4.1).
If this is just between your server and your client, simply put the additional information into the response body and use a more generic status code.
That being said -- what you called "420" is already defined as "422 Unprocessable Entity".

Using your server side language of choice you can send headers to the browser with the relevant HTTP code and message.

Related

Difference between Laravel testing method assertRedirect($uri) and assertLocation($uri)?

I was reading Laravel document HTTP tests and a question occurred.
I can't tell the difference between assertLocation($uri) and assertRedirect($uri), since both are for redirecting to specific uri.
Anyone could help would be so much appreciated.
If we look functionality of both
assertLocation($uri) would assert that the current location header matches the given URI.
But assertRedirect($uri) would assert whether the response is redirecting to a given URI.
I agree with example given by #apokryfos,
only 3xx responses are considered to be redirect responses while a 201 is not a redirect so assertLocation will pass if the response is 201 with a specified location while assertRedirect will not pass for 201 responses.
If we look code wise,
The assertRedirect() function also calls assertLocation() internally but it also checks using PHPUnit::assertTrue() that the response is redirected, if not then it will send a message
'Response status code [201] is not a redirect status code.', where 201 specifies the status code of response.
Checkout the assertRedirect() from github repo of framework

HTTP Status code and Response Body in HTTP POST for data validation

Let's suppose to have an HTTP POST that accept as input a JSON with some data and it must validate these data. The method should return also a validation message in the response body.
Ex.
{
"A" : 1,
"B" : 1,
"C" : 3
}
Suppose to have some validation rules defined over the JSON, for example (A + B) should be less than C parameter.
I have some doubts about the HTTP status code.
If the JSON is valid the HTTP POST should returns 200
If the JSON is not valid (missing parameters or wrong types) the HTTP POST should returns 400
But in case the JSON is valid (there are all the requested parameters and the types are correct) but the parameters don't respect the defined rules (A + B < C) what should be the HTTP Status?
200 and than an explanation in the response body?
400 and the explanation in the response body?
Is there the need to differentiate the HTTP Status from the Validation rules Status?
Cheers
That's what status code 422 ("Unprocessable Entity") has been designed for.
See https://www.greenbytes.de/tech/webdav/rfc4918.html#STATUS_422.
It all depends on the use-case / functionality you want to achieve.
If you want to make it easy for others to work with valid messages, I would perhaps return 2xx only if the message is completely valid, and in all other cases return 4xx. In this case the caller does not need to parse the result, which makes it easy to work with.
If the use-case is to provide some analytic service that others will use to analyze messages, not specifically to use the message itself, then I would return 2xx with the result of the analysis unless the message can not be parsed (not a json for example), in which case 4xx is warranted.
your response need to be 400 with the follwing message: "Bad Request: parameters don't respect the rules".
400 error

HTTP Requests in Laravel

In Laravel we use routes to deal with HTTP requests from the browser.
We can route a request to a controller, do some logic and then return a response.
Now, we can send in variables encapsulated with braces {} and the response can be anything, so it seems to me that routing through a controller means that the the properties of the different request methods (POST, GET, PUT etc.) are lost.
For example I could send a POST request with URI example/{id} then put in my routes.php file
Route::post('example/{id}','SomeController#SomeAction');
Then I could do something in my controller with the variable $id and send a response.
On the other hand I could send a GET request with URI example/{id} and alter my route to
Route::get('example/{id}','SomeController#SomeAction');
The controller would give the same response.
So, am I right in thinking it does not really matter what request method is used?
Two parts of your question I can identify on a second read-through:
Request methods are not lost. You have access to them with $request->getMethod(). So a GET request will return GET. You also have the method isMethod('GET') available to you, which you could use to get a truthy value which would enable you to return a different kind of response depending on the request type.
With regards to the way you set up your URL, what HTTP verb you use does matter if you're creating a REST-ful web service.
I won't explain away what a REST-ful web service is (you can look it up), here is a couple of points from your example:
If you're getting some data, you ought to be doing a GET request. It is the verb to represent a read from a resource. If you had to send a lot of data - and your intention is to add data, you ought to POST it instead.
The URI should be meaningful in a way that best describes the resource you are manipulating.
Together with the HTTP verb, you can infer the implied action. So if you are POSTing to example/1, I might infer that (and this is a digression, actually) that you are attempting to update record 1 from an example resource. In reality, you would perhaps use the PUT verb (which handles update).
Behind the scenes, Laravel uses a POST request due to browser limitations but treats it as a PUT request server-side.
Of course request type does matter. When you want to hide some request data against user and dont show it in url for example:
?username="Admin"&nick="admin1" then u will use POST otherwise you can use GET. When you want get some data u will use GET but when you want to send some data then you should use POST instead.

Conditionally Save responses to a file based on HTTP code or body string

I'm a newbie in using Jmeter and searching for a solution solving the following problem: I have a suite that contains a set of atomic HTTP requests and the goal is to save response bodies into an xml file. Currently, I'm handling that with using "Save Responses to a file listener", but need to be able to save separately error and OK responses in different XML, based on response HTTP code and body string.
to illustrate the case with dummy code
if (HTTP response code == 200 OK && body does not contain "ERROR") then
save response to file (%path%\responsename_OK.xml
else
save response to file (%path%\responsename_ERROR.xml
My bad, Nikolay, I forgot you wanted it in xml format...
Well, the easiest way is to add 2 Simple Data Writers (SDW) to each HTTP Request where 1 SDW logs only errors and the other logs only successes.
The Pro's are
it's easy and once you set it up for 1 HTTP Request, you can simply copy it to every other HTTP Request
Each success or failure with be appended to the corresponding .xml file
You can define as much or as little detail as you want
The Con is you add 2 elements to each Request, thus increasing your test size twice as much as you would with a BeanShell Assertion. (if that's a concern for you.)
If you want a more detailed way, you could try a BeanShell Assertion scripted with XML Parsers and XPath Assertions like outlined here.
Use Response Assertion (in fact you will need 2: one for Response Code and another one for Response Body checking) in order to fail the request basing on these criteria
Use If Controller for setting a condition:
${JMeterThread.last_sample_ok} will be triggered if previous sampler is successful
!${JMeterThread.last_sample_ok} - will fire if previous sampler fails
N.B. you should have any Sampler under the If Controller so it could work.

wireload / Ratatosk : How to make POST requests?

In my Cappuccino frontend I'm using Ratatosk to make queries to a RESTful JSON-based API.
When I create a new resource with
[myNewResource ensureCreated];
my backend returns the status code 201 and a Location header with the URI of the newly created resource. The response body is empty. As far as I know, that's the way a REST API should react to successful POST requests.
But upon receiving the response, Ratatosk calls
- (void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data
(in WLRemoteLink.j) and tries to decode the response body. This throws an error because the response body is empty. As a consequence, the request is repeated infinitely.
How should I go about this? Am I supposed to return the whole resource in the response body?
EDIT:
Returning the ID in the response solved the problem, like
{"id":1}
Ratatosk expects the status code 204 (no content) if the response is to be empty. Otherwise it expects the full representation of the resource which was just created (which it uses to populate server side dynamic properties locally like created_at).

Resources