0
# RESTful Web Services
1
2
JAX-RS API for building RESTful web services with annotation-driven development, comprehensive client API, and support for JSON/XML processing.
3
4
## Core Annotations
5
6
### HTTP Method Annotations
7
8
```java { .api }
9
@Target({ElementType.METHOD})
10
@Retention(RetentionPolicy.RUNTIME)
11
@HttpMethod("GET")
12
public @interface GET;
13
14
@Target({ElementType.METHOD})
15
@Retention(RetentionPolicy.RUNTIME)
16
@HttpMethod("POST")
17
public @interface POST;
18
19
@Target({ElementType.METHOD})
20
@Retention(RetentionPolicy.RUNTIME)
21
@HttpMethod("PUT")
22
public @interface PUT;
23
24
@Target({ElementType.METHOD})
25
@Retention(RetentionPolicy.RUNTIME)
26
@HttpMethod("DELETE")
27
public @interface DELETE;
28
29
@Target({ElementType.METHOD})
30
@Retention(RetentionPolicy.RUNTIME)
31
@HttpMethod("HEAD")
32
public @interface HEAD;
33
34
@Target({ElementType.METHOD})
35
@Retention(RetentionPolicy.RUNTIME)
36
@HttpMethod("OPTIONS")
37
public @interface OPTIONS;
38
```
39
40
### Path and Parameter Annotations
41
42
```java { .api }
43
@Target({ElementType.TYPE, ElementType.METHOD})
44
@Retention(RetentionPolicy.RUNTIME)
45
public @interface Path {
46
String value();
47
}
48
49
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
50
@Retention(RetentionPolicy.RUNTIME)
51
public @interface PathParam {
52
String value();
53
}
54
55
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
56
@Retention(RetentionPolicy.RUNTIME)
57
public @interface QueryParam {
58
String value();
59
}
60
61
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
62
@Retention(RetentionPolicy.RUNTIME)
63
public @interface HeaderParam {
64
String value();
65
}
66
67
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
68
@Retention(RetentionPolicy.RUNTIME)
69
public @interface FormParam {
70
String value();
71
}
72
73
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
74
@Retention(RetentionPolicy.RUNTIME)
75
public @interface MatrixParam {
76
String value();
77
}
78
79
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
80
@Retention(RetentionPolicy.RUNTIME)
81
public @interface CookieParam {
82
String value();
83
}
84
```
85
86
### Content Type Annotations
87
88
```java { .api }
89
@Target({ElementType.TYPE, ElementType.METHOD})
90
@Retention(RetentionPolicy.RUNTIME)
91
public @interface Produces {
92
String[] value() default {};
93
}
94
95
@Target({ElementType.TYPE, ElementType.METHOD})
96
@Retention(RetentionPolicy.RUNTIME)
97
public @interface Consumes {
98
String[] value() default {};
99
}
100
```
101
102
## Response Handling
103
104
### Response
105
106
```java { .api }
107
public abstract class Response implements Closeable {
108
public abstract int getStatus();
109
public abstract StatusType getStatusInfo();
110
public abstract Object getEntity();
111
public abstract <T> T readEntity(Class<T> entityType);
112
public abstract <T> T readEntity(GenericType<T> entityType);
113
public abstract <T> T readEntity(Class<T> entityType, Annotation[] annotations);
114
public abstract <T> T readEntity(GenericType<T> entityType, Annotation[] annotations);
115
public abstract boolean hasEntity();
116
public abstract boolean bufferEntity();
117
public abstract void close();
118
public abstract MultivaluedMap<String, Object> getMetadata();
119
public abstract MultivaluedMap<String, String> getStringHeaders();
120
public abstract String getHeaderString(String name);
121
122
public static ResponseBuilder status(Status status);
123
public static ResponseBuilder status(int status);
124
public static ResponseBuilder ok();
125
public static ResponseBuilder ok(Object entity);
126
public static ResponseBuilder ok(Object entity, MediaType type);
127
public static ResponseBuilder ok(Object entity, String type);
128
public static ResponseBuilder serverError();
129
public static ResponseBuilder created(URI location);
130
public static ResponseBuilder accepted();
131
public static ResponseBuilder accepted(Object entity);
132
public static ResponseBuilder noContent();
133
public static ResponseBuilder notModified();
134
public static ResponseBuilder notModified(EntityTag tag);
135
public static ResponseBuilder notModified(String tag);
136
public static ResponseBuilder seeOther(URI location);
137
public static ResponseBuilder temporaryRedirect(URI location);
138
public static ResponseBuilder notAcceptable(List<Variant> variants);
139
public static Response fromResponse(Response response);
140
}
141
```
142
143
### ResponseBuilder
144
145
```java { .api }
146
public static abstract class ResponseBuilder {
147
public abstract Response build();
148
public abstract ResponseBuilder clone();
149
public abstract ResponseBuilder status(int status);
150
public abstract ResponseBuilder status(Status status);
151
public abstract ResponseBuilder status(StatusType status);
152
public abstract ResponseBuilder entity(Object entity);
153
public abstract ResponseBuilder allow(String... methods);
154
public abstract ResponseBuilder allow(Set<String> methods);
155
public abstract ResponseBuilder cacheControl(CacheControl cacheControl);
156
public abstract ResponseBuilder encoding(String encoding);
157
public abstract ResponseBuilder header(String name, Object value);
158
public abstract ResponseBuilder replaceAll(MultivaluedMap<String, Object> headers);
159
public abstract ResponseBuilder language(String language);
160
public abstract ResponseBuilder language(Locale language);
161
public abstract ResponseBuilder location(URI location);
162
public abstract ResponseBuilder contentLocation(URI location);
163
public abstract ResponseBuilder tag(EntityTag tag);
164
public abstract ResponseBuilder tag(String tag);
165
public abstract ResponseBuilder lastModified(Date lastModified);
166
public abstract ResponseBuilder expires(Date expires);
167
public abstract ResponseBuilder cookie(NewCookie... cookies);
168
}
169
```
170
171
## Context Injection
172
173
### Context Annotations
174
175
```java { .api }
176
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
177
@Retention(RetentionPolicy.RUNTIME)
178
public @interface Context;
179
```
180
181
### UriInfo
182
183
```java { .api }
184
public interface UriInfo {
185
String getPath();
186
String getPath(boolean decode);
187
List<PathSegment> getPathSegments();
188
List<PathSegment> getPathSegments(boolean decode);
189
URI getRequestUri();
190
UriBuilder getRequestUriBuilder();
191
URI getAbsolutePath();
192
UriBuilder getAbsolutePathBuilder();
193
URI getBaseUri();
194
UriBuilder getBaseUriBuilder();
195
MultivaluedMap<String, String> getPathParameters();
196
MultivaluedMap<String, String> getPathParameters(boolean decode);
197
MultivaluedMap<String, String> getQueryParameters();
198
MultivaluedMap<String, String> getQueryParameters(boolean decode);
199
List<String> getMatchedURIs();
200
List<String> getMatchedURIs(boolean decode);
201
List<Object> getMatchedResources();
202
URI resolve(URI uri);
203
URI relativize(URI uri);
204
}
205
```
206
207
### HttpHeaders
208
209
```java { .api }
210
public interface HttpHeaders {
211
List<String> getRequestHeader(String name);
212
String getHeaderString(String name);
213
MultivaluedMap<String, String> getRequestHeaders();
214
List<MediaType> getAcceptableMediaTypes();
215
List<Locale> getAcceptableLanguages();
216
MediaType getMediaType();
217
Locale getLanguage();
218
Map<String, Cookie> getCookies();
219
Date getDate();
220
int getLength();
221
}
222
```
223
224
### SecurityContext
225
226
```java { .api }
227
public interface SecurityContext {
228
Principal getUserPrincipal();
229
boolean isUserInRole(String role);
230
boolean isSecure();
231
String getAuthenticationScheme();
232
233
String BASIC_AUTH = "BASIC";
234
String FORM_AUTH = "FORM";
235
String CLIENT_CERT_AUTH = "CLIENT_CERT";
236
String DIGEST_AUTH = "DIGEST";
237
}
238
```
239
240
## Client API
241
242
### Client
243
244
```java { .api }
245
public interface Client extends Configurable<Client>, AutoCloseable {
246
void close();
247
WebTarget target(String uri);
248
WebTarget target(URI uri);
249
WebTarget target(UriBuilder uriBuilder);
250
Invocation.Builder invocation(Link link);
251
}
252
```
253
254
### WebTarget
255
256
```java { .api }
257
public interface WebTarget extends Configurable<WebTarget> {
258
URI getUri();
259
UriBuilder getUriBuilder();
260
WebTarget path(String path);
261
WebTarget resolveTemplate(String name, Object value);
262
WebTarget resolveTemplate(String name, Object value, boolean encodeSlashInPath);
263
WebTarget resolveTemplateFromEncoded(String name, Object value);
264
WebTarget resolveTemplates(Map<String, Object> templateValues);
265
WebTarget resolveTemplates(Map<String, Object> templateValues, boolean encodeSlashInPath);
266
WebTarget resolveTemplatesFromEncoded(Map<String, Object> templateValues);
267
WebTarget matrixParam(String name, Object... values);
268
WebTarget queryParam(String name, Object... values);
269
Invocation.Builder request();
270
Invocation.Builder request(String... acceptedResponseTypes);
271
Invocation.Builder request(MediaType... acceptedResponseTypes);
272
}
273
```
274
275
### Invocation.Builder
276
277
```java { .api }
278
public static interface Builder extends SyncInvoker, AsyncInvoker {
279
Invocation build(String method);
280
Invocation build(String method, Entity<?> entity);
281
Invocation buildGet();
282
Invocation buildDelete();
283
Invocation buildPost(Entity<?> entity);
284
Invocation buildPut(Entity<?> entity);
285
AsyncInvoker async();
286
Invocation.Builder accept(String... mediaTypes);
287
Invocation.Builder accept(MediaType... mediaTypes);
288
Invocation.Builder acceptLanguage(Locale... locales);
289
Invocation.Builder acceptLanguage(String... locales);
290
Invocation.Builder acceptEncoding(String... encodings);
291
Invocation.Builder cookie(Cookie cookie);
292
Invocation.Builder cookie(String name, String value);
293
Invocation.Builder cacheControl(CacheControl cacheControl);
294
Invocation.Builder header(String name, Object value);
295
Invocation.Builder headers(MultivaluedMap<String, Object> headers);
296
Invocation.Builder property(String name, Object value);
297
}
298
```
299
300
## Application Configuration
301
302
### Application
303
304
```java { .api }
305
public abstract class Application {
306
public Set<Class<?>> getClasses();
307
public Set<Object> getSingletons();
308
public Map<String, Object> getProperties();
309
}
310
```
311
312
### ApplicationPath
313
314
```java { .api }
315
@Target({ElementType.TYPE})
316
@Retention(RetentionPolicy.RUNTIME)
317
public @interface ApplicationPath {
318
String value();
319
}
320
```
321
322
## Media Types
323
324
### MediaType
325
326
```java { .api }
327
public class MediaType {
328
public static final String WILDCARD = "*/*";
329
public static final String APPLICATION_XML = "application/xml";
330
public static final String APPLICATION_ATOM_XML = "application/atom+xml";
331
public static final String APPLICATION_XHTML_XML = "application/xhtml+xml";
332
public static final String APPLICATION_SVG_XML = "application/svg+xml";
333
public static final String APPLICATION_JSON = "application/json";
334
public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded";
335
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
336
public static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
337
public static final String TEXT_PLAIN = "text/plain";
338
public static final String TEXT_XML = "text/xml";
339
public static final String TEXT_HTML = "text/html";
340
341
public static final MediaType WILDCARD_TYPE = new MediaType();
342
public static final MediaType APPLICATION_XML_TYPE = new MediaType("application", "xml");
343
public static final MediaType APPLICATION_JSON_TYPE = new MediaType("application", "json");
344
public static final MediaType TEXT_PLAIN_TYPE = new MediaType("text", "plain");
345
public static final MediaType TEXT_HTML_TYPE = new MediaType("text", "html");
346
347
public MediaType();
348
public MediaType(String type, String subtype);
349
public MediaType(String type, String subtype, Map<String, String> parameters);
350
public MediaType(String type, String subtype, String charset);
351
352
public String getType();
353
public boolean isWildcardType();
354
public String getSubtype();
355
public boolean isWildcardSubtype();
356
public Map<String, String> getParameters();
357
public MediaType withCharset(String charset);
358
public boolean isCompatible(MediaType other);
359
public static MediaType valueOf(String type);
360
}
361
```
362
363
## Usage Examples
364
365
### Basic REST Resource
366
367
```java
368
@Path("/users")
369
@ApplicationScoped
370
public class UserResource {
371
372
@Inject
373
private UserService userService;
374
375
@GET
376
@Produces(MediaType.APPLICATION_JSON)
377
public List<User> getAllUsers() {
378
return userService.findAll();
379
}
380
381
@GET
382
@Path("/{id}")
383
@Produces(MediaType.APPLICATION_JSON)
384
public Response getUser(@PathParam("id") Long id) {
385
User user = userService.findById(id);
386
if (user != null) {
387
return Response.ok(user).build();
388
} else {
389
return Response.status(Response.Status.NOT_FOUND).build();
390
}
391
}
392
393
@POST
394
@Consumes(MediaType.APPLICATION_JSON)
395
@Produces(MediaType.APPLICATION_JSON)
396
public Response createUser(User user, @Context UriInfo uriInfo) {
397
User created = userService.create(user);
398
URI location = uriInfo.getAbsolutePathBuilder()
399
.path(created.getId().toString())
400
.build();
401
return Response.created(location).entity(created).build();
402
}
403
404
@PUT
405
@Path("/{id}")
406
@Consumes(MediaType.APPLICATION_JSON)
407
@Produces(MediaType.APPLICATION_JSON)
408
public Response updateUser(@PathParam("id") Long id, User user) {
409
user.setId(id);
410
User updated = userService.update(user);
411
return Response.ok(updated).build();
412
}
413
414
@DELETE
415
@Path("/{id}")
416
public Response deleteUser(@PathParam("id") Long id) {
417
userService.delete(id);
418
return Response.noContent().build();
419
}
420
}
421
```
422
423
### JAX-RS Client Usage
424
425
```java
426
// Create client and target
427
Client client = ClientBuilder.newClient();
428
WebTarget target = client.target("http://localhost:8080/api/users");
429
430
// GET request
431
List<User> users = target.request(MediaType.APPLICATION_JSON)
432
.get(new GenericType<List<User>>() {});
433
434
// POST request
435
User newUser = new User("John Doe", "john@example.com");
436
Response response = target.request()
437
.post(Entity.json(newUser));
438
439
// PUT request with path parameter
440
User updatedUser = new User("Jane Doe", "jane@example.com");
441
response = target.path("/{id}")
442
.resolveTemplate("id", 1)
443
.request()
444
.put(Entity.json(updatedUser));
445
446
// DELETE request
447
response = target.path("/{id}")
448
.resolveTemplate("id", 1)
449
.request()
450
.delete();
451
452
client.close();
453
```
454
455
### Application Configuration
456
457
```java
458
@ApplicationPath("/api")
459
public class RestApplication extends Application {
460
@Override
461
public Set<Class<?>> getClasses() {
462
Set<Class<?>> resources = new HashSet<>();
463
resources.add(UserResource.class);
464
resources.add(ProductResource.class);
465
return resources;
466
}
467
}