http delete with REST - rest

I am currently using Jersey Framework (JAX-RS implementation) for building RESTful Web Services. The Resource classes in the project have implemented the standard HTTP operations - GET,POST & DELETE. I am trying to figure out how to send request parameters from client to these methods.
For GET it would be in the query string(extract using #QueryParam) and POST would be name/value pair list (extract using #FormParam) sent in with the request body. I tested them using HTTPClient and worked fine. For DELETE operation, I am not finding any conclusive answers on the parameter type/format. Does DELETE operation receive parameters in the query string(extract using #QueryParam) or in the body(extract using #FormParam)?
In most DELETE examples on the web, I observe the use of #PathParam annotation for parameter extraction(this would be from the query string again).
Is this the correct way of passing parameters to the DELETE method? I just want to be careful here so that I am not violating any REST principles.

Yes, its up to you, but as I get REST ideology, DELETE URL should delete something that is returned by a GET URL request. For example, if
GET http://server/app/item/45678
returns item with id 45678,
DELETE http://server/app/item/45678
should delete it.
Thus, I think it is better to use PathParam than QueryParam, when QueryParam can be used to control some aspects of work.
DELETE http://server/app/item/45678?wipeData=true

The DELETE method should use the URL to identify the resource to delete. This means you can use either path parameters or query parameters.
Beyond that, there is no right and wrong way to construct an URL as far as REST is concerned.

You can use like this
URL is http://yourapp/person/personid
#DELETE
#Path("/person/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response deletePerson(#PathParam("id") String id){
Result result = new Result();
try{
persenService.deletePerson(id);
result.setResponce("success");
}
catch (Exception e){
result.setResponce("fail");
e.printStackTrace();
}
return Response.status(200).entity(result).build();
}

#QueryParam would be the correct way. #PathParam is only for things before any url parameters (stuff after the '?'). And #FormParam is only for submitted web forms that have the form content type.

Related

{guzzle-services} How to use middlewares with GuzzleClient client AS OPPOSED TO directly with raw GuzzleHttp\Client?

My middleware need is to:
add an extra query param to requests made by a REST API client derived from GuzzleHttp\Command\Guzzle\GuzzleClient
I cannot do this directly when invoking APIs through the client because GuzzleClient uses an API specification and it only passes on "legal" query parameters. Therefore I must install a middleware to intercept HTTP requests after the API client prepares them.
The track I am currently on:
$apiClient->getHandlerStack()-push($myMiddleware)
The problem:
I cannot figure out the RIGHT way to assemble the functional Russian doll that $myMiddleware must be. This is an insane gazilliardth-order function scenario, and the exact right way the function should be written seems to be different from the extensively documented way of doing things when working with GuzzleHttp\Client directly. No matter what I try, I end up having wrong things passed to some layer of the matryoshka, causing an argument type error, or I end up returning something wrong from a layer, causing a type error in Guzzle code.
I made a carefully weighted decision to give up trying to understand. Please just give me a boilerplate solution for GuzzleHttp\Command\Guzzle\GuzzleClient, as opposed to GuzzleHttp\Client.
The HandlerStack that is used to handle middleware in GuzzleHttp\Command\Guzzle\GuzzleClient can either transform/validate a command before it is serialized or handle the result after it comes back. If you want to modify the command after it has been turned into a request, but before it is actually sent, then you'd use the same method of Middleware as if you weren't using GuzzleClient - create and attach middleware to the GuzzleHttp\Client instance that is passed as the first argument to GuzzleClient.
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Command\Guzzle\GuzzleClient;
use GuzzleHttp\Command\Guzzle\Description;
class MyCustomMiddleware
{
public function __invoke(callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
// ... do something with request
return $handler($request, $options);
}
}
}
$handlerStack = HandlerStack::create();
$handlerStack->push(new MyCustomMiddleware);
$config['handler'] = $handlerStack;
$apiClient = new GuzzleClient(new Client($config), new Description(...));
The boilerplate solution for GuzzleClient is the same as for GuzzleHttp\Client because regardless of using Guzzle Services or not, your request-modifying middleware needs to go on GuzzleHttp\Client.
You can also use
$handler->push(Middleware::mapRequest(function(){...});
Of sorts to manipulate the request. I'm not 100% certain this is the thing you're looking for. But I assume you can add your extra parameter to the Request in there.
private function createAuthStack()
{
$stack = HandlerStack::create();
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('Authorization', "Bearer " . $this->accessToken);
}));
return $stack;
}
More Examples here: https://hotexamples.com/examples/guzzlehttp/Middleware/mapRequest/php-middleware-maprequest-method-examples.html

Controller return type and httpStatus best practice and production/consumption on method in REST WS

I commence in REST and I have some questions:
What type must the controller return? Typically, I'm asking if my Rest #Controller must return Item object as it is or encapsulate it in ResponseEntity in order to specify http-status-code.
What http status code to use in a GET method on a particular item ("/items/2") if the given item does not exists: HttpMediaStatus.OK(200) and null return or HttpStatus.NO_CONTENT(204) and null return ?
Second part: I saw it was possible to specify #Produces and #Consumes on WS method but what the use of that? My application and my methods work so, why specify MediaType.APPLICATION_JSON_VALUE? Doesn't Spring/SpringBoot automatically convert Item or ResponseEntity into json?
Context: using Spring Boot, hibernate, REST webservice.
Thank you.
Many questions in one, I'll provide short answers with a bunch of link to relevant articles and the reference documentation.
What type must the controller return?
Depends on your annotation and the RESTful-ness of your service. There are three annotations you can use for controllers: #Controller, #RestController and #RepositoryRestController.
Controller is the base annotation to mark your class as a controller. The return type of the controller endpoint methods can be many things, I invite you to read this dedicated post to get a grasp of it.
When developing a pure-REST service, you will focus on using RestController and RepositoryRestController.
RestControlleris Controller + ResponseBody. It binds the return value of the endpoint method to the web response body:
#RestController
public ItemController {
#RequestMapping("/items/{id}")
public Item getItem(#PathVariable("id") String id) {
Item item = ...
return item;
}
}
With this, when you hit http:/.../api/items/foo, Spring does its magic, automatically converting the item to a ResponseEntity with a relevant 40X status code and some default HTTP headers.
At some point, you will need more control over the status code and headers, while still benefiting from Spring Data REST's settings. That's when you will use RepositoryRestController with a ResponseEntity<Item> as return type, see the example the Spring Data REST reference.
What http status code to use in a GET method on a particular item if the given item does not exists?
Bluntly said: use HttpStatus.NOT_FOUND. You're looking for a resource that does not exist, there's something wrong.
That being said, it is completely up to you to decide how to handle missing resources in your project. If your workflow justifies it, a missing resource could be something completely acceptable that indeed returns a 20X response, though you may expect users of your API to get confused if you haven't warned them or provided some documentation (we are creatures of habits and conventions). But I'd still start with a 404 status code.
(...) #Produces and #Consumes on WS method but what the use of that? My application and my methods work so, why specify MediaType.APPLICATION_JSON_VALUE? Doesn't Spring/SpringBoot automatically convert Item or ResponseEntity into json?
#Consumes and #Produces are respectively matched against content-type and accept headers from the request. It's a mean of restricting the input accepted and the output provided by your endpoint method.
Since we're talking about a REST service, communications between clients of the API and the service are expected to be JSON-formatted. Thanks to Spring HATEOAS, the answer are actually formatted with the application/hal+json content-type.
In that scenario, you can indeed not bother with those two annotations. You will need them if you develop a service that accepts different content-types (application/text, application/json, application/xml...) and provides, for instance, HTML views to users of your website and JSON or XML response to automated clients of your service.
For real life examples:
Facebook provides the Graph API for applications to read to/write from its graph, while users happily (?) surf on web pages
Google does the same with the Google Maps API

Why does one HTTP GET request retrieve the required data and another retrieve []

I'm currently working on ng-admin.
I'm having a problem retrieving user data from my REST API (connected to a MongoDB) and displaying it.
I have identified the problem as the following:
When I enter http://localhost:3000/users into my browser, I get a list of all users in my database.
When I enter http://localhost:3000/users?_page=1&_perPage=30&_sortDir=DESC&_sortField=id,
I get [] as a result.
I am quite new to this, I used both my browser and the POSTMAN Chrome extension to test this and get the same result.
http://localhost:3000/users_end=30&_order=DESC&_sort=id&_start=0
This (/users_end) is a different request than /users.
It should be:
http://localhost:3000/users?end=30&_order=DESC&_sort=id&_start=0
Or, by looking at the other parameters:
http://localhost:3000/users?_end=30&_order=DESC&_sort=id&_start=0
with end or _end being the first parameter (mark the ?).
Update (it is ? and before the _, I have edited.):
If adding parameters to the request returns an empty list, try adding only one at a time to narrow down the problem (there's probably an error in the usage of those parameters - are you sure you need those underscores?).
Your REST API must have a way to handle pagination, sorting, and filtering. But ng-admin cannot determine exactly how, because REST is a style and not a standard. So ng-admin makes assumptions about how your API does that by default, that's why it adds these _end and _sort query parameters.
In order to transform these parameters into those that your API understands, you'll have to add an interceptor. This is all thoroughly explained in the ng-admin documentation: http://ng-admin-book.marmelab.com/doc/API-mapping.html

Mapping Querystring Parameters to Resource Methods in JAX-RS

Amazon's web API uses a "query API" for non-CRUD operations by using a querystring parameter to specify the operation. I want to implement non-CRUD operations in a similar manner.
Is there any way to map a POST resource method using Jersey JAX-RS dependent on the value of a particular querystring parameter? For example I would like to do something like this:
#POST #Query(name="xaction", value="move")
public Response move(#QueryParam("source") String source, #QueryParam("dest") String dest)
{
...
}
#POST #Query(name="xaction", value="copy")
public Response copy(#QueryParam("source") String source, #QueryParam("dest") String dest)
{
...
}
In the above example I would expect a framework would dispatch to the appropriate method depending on the value of the "xaction" querystring parameter regardless of URI path. Unfortunately I do not have the luxury of using paths or methods to distinguish these operations. I am open to other library suggestions that are compatible with JAX-RS or custom implementations to resolve this.
REST is not Remote Procedure Call (RPC). Even if Amazon is publishing an API like this, it is still not RESTful.
JAX-RS does not provide a mapping you describe for good reasons. Every Resource must be uniquely identifiable by the URI which includes the full path and all query parameters. URI like you describe don't identify Resources but call procedures.
Ask yourself these questions:
What are your Resources?
Do actions on Resources easily map to HTTP verbs?
If not, can actions on Resources me modeled as Resources?
As example for 3., you could thing about a MoveResource and a CopyReource.
A JSON Representation of a MoveResource could look like this:
{
"source": "/path/to/source",
"dest": "/path/to/dest"
}
Creating such a MoveResource and thus triggering a move could be done by a POST to the collection Resource at /moves. This POST would return 201 Created with a Location header like /moves/42. A GET to this Resource could return the state of the MoveResource:
{
"source": "/path/to/source",
"dest": "/path/to/dest",
"status": "success"
}
The same could be done for a CopyResource.

Url as path parameter in restful api causes bad request

We are developing a restful api using jersey (1.9.1) and tomcat 5.5.
A given resource is identified with a urn and we would like to address a specific instance of that resource. In order to achieve this, we used the following code:
#Path("/XXXs")
public interface XXXResource {
#GET
#Path("{id}")
#Produces({ MediaType.APPLICATION_JSON })
XXXInfo getXXX(#PathParam("id") String id);
}
The idea is to address this resource using the following url:
http://localhost:8080/restapi/XXXs/http%3A%2F%2Fns.something.com%2FXXX%2F2
The decoded path param value should be:
http://ns.something.com/XXX/2
However, when I make the request using the encoded url I get a bad request message from tomcat. So my questions are:
Is it correct to use a Urn as a path parameter?
Why is tomcat considering this request as a bad request?
Just in case, I changed the signature of the method so that the parameter is taken from the query string and it worked fine, but I want the parameter to be part of the path.
Thanks.
Ok, I solved it by adding the following line in catalina.properties:
org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true