JAX-RS has annotations for HTTP verbs such as GET
(@GET
) and POST
(@POST
) but there is no @PATCH
annotation. How
I got answer here.
One will just have to define a custom Patch annotation, what that means is that you will have to write a PATCH.java file with following code:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
public @interface PATCH {
}
Import the package containing PATCH.java and then you can use it like other HTTP method annotations:
@PATCH
@Path("/data/{keyspace}")
@Produces({ "application/json" })
public void patchRow(@PathParam("keyspace") String keyspace, String body)
throws Exception
I used this @PATCH to send some JSON to my REST service.
JAX-RS API 2.0.1 doesn't have PATCH. But, looking at JAX-RS API 2.2-SNAPSHOT code, PATCH is now included. The code is:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod(HttpMethod.PATCH)
@Documented
public @interface PATCH {
}
Here is the link.
You might use the same codes for remedy until 2.2 is out. For HttpMethod.PATCH, just replace it with "PATCH".
JAX-RS 2.1 added @PATCH to the list of supported HTTP methods.
When using Swagger to document a REST API, you could use the existing @PATCH annotation defined in the io.swagger.jaxrs
package.
Dropwizard defines a @PATCH annotation in the io.dropwizard.jersey
package.
If the above mentioned approaches don't work for you, you can write your own @PATCH
annotation:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
public @interface PATCH { }
The @HttpMethod annotation is used to associate the name of a HTTP method with an annotation, creating a what the JAX-RS specification calls resource method designator.
Your own @PATCH
annotation should work fine in Swagger.
If you are using CXF 3.1.2 or later (source), you can use org.apache.cxf.jaxrs.ext.PATCH
.
In Jersey this will work just fine, but when using Jersey Client to test your resource class, you will get exceptions:
java.net.ProtocolException: Invalid HTTP method: PATCH
There is a workaround for this, by setting client property
HttpUrlConnectorProvider.SET_METHOD_WORKAROUND
But wait, then you will end up with the following exception:
javax.ws.rs.ProcessingException: java.net.ProtocolException: HTTP method PATCH doesn't support output
So there is no other way than changing to the Apache HTTP client library, using Jersey version 2.10, its easy to configure to use Apache HTTP client, you only need to override the client config method in your test class that extends JerseyTest
.
@Override
protected void configureClient(ClientConfig config) {
config.register(CustomJacksonJsonProvider.class);
ConnectorProvider connectorProvider = new ApacheConnectorProvider();
config.connectorProvider(connectorProvider);
}
And you need to also add another Maven dependency, jersey-apache-connector
and jersey-test-framework-provider-external
, see Jersey doc