WebApi response codes - asp.net-web-api

So let's say I have a WebApi controller called UsersController. Let's look at the following examples:
1.Navigating to /Users/1 returns JSON of a user with Id = 1. HTTP response code will be 200.
2.Navigating to /User/1 (note I misspelled the URL!) will return response code 404. I do not even need to do anything, my web server will return code 404 for me.
Now the question: what response code (200 or 404) should be returned by the URL /Users/2, if user with Id = 2 does not exist in the database? And why.

You should return NotFound (404), because the url is valid but the required resource doesn't exists. check this.

Related

POST request response being sent in weird format

I intend to send my server response in the following format
Api Doc
I did the following
headersR.add("response_code", "OK");
headersR.add("cmd_code", "SET_FK_NAME");
headersR.add("trans_id", Long.toString(System.currentTimeMillis()/1000000));
JSONPObject map1 = new JSONPObject("fk_name", "jj");
return new ResponseEntity<>(map1, headersR, HttpStatus.OK);
I was getting a negative response from the other side so I checked Wireshark(Had a hard time logging my response body). And I got this in Wireshark.
Wirehark Screenshot
The response body is Definitely not JSON.
How can I fix this?
The response body fk_name("jj") is not JSON, it's JSONP -- Browser would take the function name fk_name and try to execute it with "jj" as parameter.
The root cause is you are using JSONPObject, whose constructor accepts 2 parameters: a function name, and the data value. Not the expected JSON key and value.
To fix this issue and return {"fk_name":"jj"}, remove the JSONPObject stuff and use code as follow:
return new ResponseEntity<>("{\"fk_name\":\"jj\"}", headersR, HttpStatus.OK);

Request method is always same when endpoint called using Postman

Using POSTMANto call an endpoint for example:
http://localhost/v1
Checking Request Method in the code using:
context.getRequest().getMethod()
No matter what I change request method in postman request, I always get the first request method I select let say GET.
When i change request to
http://localhost/v1/
It works and start sending correct request methods i select in POSTMAN
http://localhost/v1
I am expecting that when I call:
http://localhost/v1
or
http://localhost/v1/
It should behave same way.
Any explanation to point to the right direction would be appreciated
you need to redirect /v1 to /v1/ try like
#RequestMapping(value="/v1")
public ModelAndView redirectToPage() {
return new ModelAndView("redirect:/v1/");
}

Django ajax warning on same page after DoesNotExist exception on form POST

I have a django form attached to a view. In the form a user types in a query which is passed to a Model.objects.get( query ) like so:
def post(self, request):
try:
Model.objects.get(query)
except Model.DoesNotExist:
# something here
Upon exception i'd like to send an ajax request to my template that stops it from refreshing, and displays a warning to the user that there's nothing in the database matching that get request. What would I put in the view and the template?
The http standard response would be a 404 response. Django has a shortcut function for this: get_object_or_404
def post(self, request):
my_object = get_object_or_404(Model, query)
If the lookup fails, django will raise an 404 error, which will result in a 404 http response back to the client. In your javascript ajax handling code, you should check the http status, and handle any 404 responses appropriately.
For example, if you are using the fetch api, the code might look like this.
fetch('/some/url/?query=foobar').then(response => {
if (response.ok) return response.json()
if (response.status == 404) throw new Error('404')
})

Laravel 5.5 Request is empty in Restful controller

I have such a route in my routes/web.php
Route::resource('/api/surveys', 'SurveyController');
As documentation says, it creates all needed routes for API. This is a function, that gets executed when I go for /api/surveys route:
public function index()
{
$request = request();
if(!$request->hasHeader('token')) {
return "No auth token found.";
}
$tokenCheck = $this->userService->isTokenValid($request->header('token'));
if($tokenCheck !== true) {
return $tokenCheck;
}
return $this->surveyService->all();
}
What it does, it checks if token header parameter is set, if not, it returns an error, if yes, it checks if token is valid and etc. if everything is OK, it should return surveys from database.
public function surveys() {
$request = \Request::create('/api/surveys', 'GET');
$request->headers->set('Accept', 'application/json');
$request->headers->set('token', \Cookie::get('token'));
$response = \Route::dispatch($request);
print_r('<pre>');
print_r($response);
print_r('</pre>');
}
I have a website, that should use that API I just created to get all survey records. I create a new request object, set header "token" with token I get from a cookie and then try to dispatch and get a response. But the problem is that everytime I get "No auth token found." error. That means $request->hasHeader('token') returns false, even tough I set it here in my request. If I print_r $request->all() in Restful controller, I get an empty array.
I tried Postman to access this API with token parameter, and it works fine in postman, but here, it seems that Request disappears while it travels to API controller.
What I did wrong here?
When you manually create a request and dispatch it, that works to get the routing to call the correct controller, however that does not affect the request that is bound in the container.
When your "fake" request is handled by the api controller, the request that it pulls out of the container is the original "real" request that was made by the user.
Instead of dispatching the route with your new request, you will need to app()->handle($request) the new request. This, however, will completely replace the original "real" request with your new "fake" request, so everything from the original request will be lost.
Having said all that, this method of consuming your own api is discouraged, even by Taylor. You can read his comment on this Github issue. So, consuming your own api like this may work, but you may also run into some other unforeseen issues.
The more appropriate solution would be to extract out the logic called by the api routes to another class, and then call that extracted logic from both your api routes and your web routes.

MVC 3 + REST return custom http error?

In my application I am trying to get it so that when a REST api call is made, if there is an error that it return a proper status code then either Json or Xml in the body of the response.
So 400: { 'ErrorCode': '400', 'Reason' : 'You did something wrong..' }
or 400: <Error><ErrorCode>400</ErrorCode><Reason>You did something wrong</Reason></Error>
However I can't seem to find how to set the status and body to make this happen. Using fiddler inspect whats being passed back and fourth I've found that if I return a normal ActionResult then I can return the body message ok but the status is 200. If I use HttpException then I can set the status code but the body message is returned as a large html document. I've tried using HttpStatusCodeResult but that just seems to fail and return a 302.
I'm a bit stumped.
Try Response.StatusCode = (int)HttpStatusCode.BadRequest; in your action method. Check out this article at develoq for a short tutorial: http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/
Web API can handle this in various ways, but if you want to stick to ASP.NET MVC then use the code below:
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return Content("Error description goes here.", "text/plain");
Check out MVC 4 Beta, there is a new feature called Web API that will help you solve this issue.

Resources