CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-javax-ws-rs--javax-ws-rs-api

Java API for RESTful Web Services

Pending
Overview
Eval results
Files

resource-endpoints.mddocs/

Resource Endpoints

The resource endpoints capabilities provide the core annotations and mechanisms for defining REST endpoints, mapping HTTP methods, and injecting request parameters into Java methods.

Core Imports

import javax.ws.rs.Path;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.PATCH;

import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.BeanParam;
import javax.ws.rs.DefaultValue;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.Encoded;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.Request;

Path Definition

@Path Annotation

Identifies the URI path template for resources and sub-resources.

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Path {
    String value();
}

Usage Example:

@Path("/users")
public class UserResource {
    
    @GET
    @Path("/{id}")
    public Response getUser(@PathParam("id") String userId) {
        // Implementation
        return Response.ok().build();
    }
    
    @GET  
    @Path("/{id}/orders/{orderId}")
    public Response getUserOrder(@PathParam("id") String userId,
                                @PathParam("orderId") String orderId) {
        // Nested path parameters
        return Response.ok().build();
    }
}

@ApplicationPath Annotation

Identifies the application path that serves as the base URI for all resource URIs provided by @Path annotations.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApplicationPath {
    String value();
}

Usage Example:

@ApplicationPath("/api/v1")
public class MyApplication extends Application {
    // Optional: configure resource classes, singletons, providers
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(UserResource.class);
        classes.add(OrderResource.class);
        return classes;
    }
}

HTTP Method Annotations

Standard HTTP Methods

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("GET")
@Documented
public @interface GET {
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("POST")
@Documented
public @interface POST {
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PUT")
@Documented
public @interface PUT {
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("DELETE")
@Documented
public @interface DELETE {
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("HEAD")
@Documented
public @interface HEAD {
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("OPTIONS")
@Documented
public @interface OPTIONS {
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
@Documented
public @interface PATCH {
}

Usage Example:

@Path("/products")
public class ProductResource {
    
    @GET
    public List<Product> getAllProducts() {
        return productService.findAll();
    }
    
    @POST
    public Response createProduct(Product product) {
        Product created = productService.save(product);
        return Response.status(Response.Status.CREATED).entity(created).build();
    }
    
    @PUT
    @Path("/{id}")
    public Response updateProduct(@PathParam("id") String id, Product product) {
        Product updated = productService.update(id, product);
        return Response.ok(updated).build();
    }
    
    @DELETE
    @Path("/{id}")
    public Response deleteProduct(@PathParam("id") String id) {
        productService.delete(id);
        return Response.noContent().build();
    }
    
    @PATCH
    @Path("/{id}")
    public Response patchProduct(@PathParam("id") String id, 
                                Map<String, Object> updates) {
        Product patched = productService.patch(id, updates);
        return Response.ok(patched).build();
    }
}

Custom HTTP Methods

@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HttpMethod {
    String value();
}

Usage Example:

// Define custom HTTP method annotation
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PURGE")
@Documented
public @interface PURGE {
}

// Use custom method
@Path("/cache")
public class CacheResource {
    
    @PURGE
    @Path("/{key}")
    public Response purgeCache(@PathParam("key") String cacheKey) {
        cacheService.purge(cacheKey);
        return Response.noContent().build();
    }
}

Parameter Injection Annotations

Path Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathParam {
    String value();
}

Query Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface QueryParam {
    String value();
}

Header Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HeaderParam {
    String value();
}

Cookie Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CookieParam {
    String value();
}

Form Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FormParam {
    String value();
}

Matrix Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MatrixParam {
    String value();
}

Bean Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BeanParam {
}

Parameter Injection Usage Examples:

@Path("/search")
public class SearchResource {
    
    @GET
    @Path("/{category}")
    public Response search(@PathParam("category") String category,
                          @QueryParam("q") String query,
                          @QueryParam("limit") @DefaultValue("10") int limit,
                          @QueryParam("offset") @DefaultValue("0") int offset,
                          @HeaderParam("Accept-Language") String language,
                          @HeaderParam("User-Agent") String userAgent,
                          @CookieParam("sessionId") String sessionId) {
        
        SearchRequest request = new SearchRequest(category, query, limit, offset);
        request.setLanguage(language);
        request.setUserAgent(userAgent);
        request.setSessionId(sessionId);
        
        SearchResults results = searchService.search(request);
        return Response.ok(results).build();
    }
    
    // Matrix parameters example: /products;color=red;size=large
    @GET
    @Path("/products")
    public Response findProducts(@MatrixParam("color") String color,
                                @MatrixParam("size") String size,
                                @MatrixParam("brand") List<String> brands) {
        ProductFilter filter = new ProductFilter(color, size, brands);
        List<Product> products = productService.findByFilter(filter);
        return Response.ok(products).build();
    }
    
    // Form parameters for POST requests
    @POST
    @Path("/contact")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response submitContactForm(@FormParam("name") String name,
                                     @FormParam("email") String email,
                                     @FormParam("message") String message,
                                     @FormParam("subscribe") boolean subscribe) {
        
        ContactSubmission submission = new ContactSubmission(name, email, message, subscribe);
        contactService.submit(submission);
        return Response.ok().build();
    }
}

Bean Parameter Example

// Parameter aggregator class
public class SearchParams {
    @QueryParam("q")
    private String query;
    
    @QueryParam("limit") 
    @DefaultValue("10")
    private int limit;
    
    @QueryParam("offset")
    @DefaultValue("0") 
    private int offset;
    
    @HeaderParam("Accept-Language")
    private String language;
    
    // Getters and setters...
}

@Path("/items")
public class ItemResource {
    
    @GET
    public Response searchItems(@BeanParam SearchParams params) {
        List<Item> items = itemService.search(params);
        return Response.ok(items).build();
    }
}

Default Values

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DefaultValue {
    String value();
}

Content Negotiation

@Consumes Annotation

Specifies the media types that a resource method can accept.

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Consumes {
    String[] value() default {"*/*"};
}

@Produces Annotation

Specifies the media types that a resource method can produce.

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Produces {
    String[] value() default {"*/*"};
}

Content Negotiation Examples:

@Path("/api/v1/users")
@Produces(MediaType.APPLICATION_JSON) // Default for all methods in class
public class UserApiResource {
    
    @GET
    @Path("/{id}")
    public User getUser(@PathParam("id") String id) {
        // Returns JSON by default
        return userService.findById(id);
    }
    
    @GET
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public User getUserWithXml(@PathParam("id") String id) {
        // Can return either XML or JSON based on Accept header
        return userService.findById(id);
    }
    
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createUser(User user) {
        // Only accepts JSON input
        User created = userService.create(user);
        return Response.status(Response.Status.CREATED).entity(created).build();
    }
    
    @PUT
    @Path("/{id}")
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateUser(@PathParam("id") String id, User user) {
        // Accepts both JSON and XML input, returns JSON
        User updated = userService.update(id, user);
        return Response.ok(updated).build();
    }
    
    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadUserAvatar(@PathParam("id") String userId,
                                    @FormParam("file") InputStream fileStream,
                                    @FormParam("filename") String filename) {
        avatarService.upload(userId, fileStream, filename);
        return Response.ok().build();
    }
}

Encoding Control

@Encoded Annotation

Disables automatic URI decoding for parameter values.

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD,
         ElementType.CONSTRUCTOR, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Encoded {
}

Usage Example:

@Path("/files")
public class FileResource {
    
    @GET
    @Path("/{filename}")
    public Response getFile(@PathParam("filename") @Encoded String encodedFilename,
                           @QueryParam("path") @Encoded String encodedPath) {
        // Parameters remain URL-encoded, useful for filenames with special chars
        String actualFilename = URLDecoder.decode(encodedFilename, "UTF-8");
        String actualPath = URLDecoder.decode(encodedPath, "UTF-8");
        
        File file = fileService.getFile(actualPath, actualFilename);
        return Response.ok(file).build();
    }
}

Context Injection

JAX-RS provides several context objects that can be injected into resource methods:

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Context {
}

Common Context Types:

@Path("/info")  
public class InfoResource {
    
    @GET
    public Response getRequestInfo(@Context UriInfo uriInfo,
                                  @Context HttpHeaders headers,
                                  @Context SecurityContext securityContext) {
        
        Map<String, Object> info = new HashMap<>();
        info.put("requestUri", uriInfo.getRequestUri().toString());
        info.put("baseUri", uriInfo.getBaseUri().toString());
        info.put("pathParameters", uriInfo.getPathParameters());
        info.put("queryParameters", uriInfo.getQueryParameters());
        info.put("userPrincipal", securityContext.getUserPrincipal());
        info.put("acceptHeader", headers.getHeaderString("Accept"));
        
        return Response.ok(info).build();
    }
}

Types

Media Type Constants

public class MediaType {
    public static final String APPLICATION_JSON = "application/json";
    public static final String APPLICATION_XML = "application/xml";
    public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded";
    public static final String MULTIPART_FORM_DATA = "multipart/form-data";
    public static final String TEXT_PLAIN = "text/plain";
    public static final String TEXT_HTML = "text/html";
    public static final String TEXT_XML = "text/xml";
    public static final String WILDCARD = "*/*";
    
    public static final MediaType APPLICATION_JSON_TYPE = new MediaType("application", "json");
    public static final MediaType APPLICATION_XML_TYPE = new MediaType("application", "xml");
    public static final MediaType TEXT_PLAIN_TYPE = new MediaType("text", "plain");
    public static final MediaType WILDCARD_TYPE = new MediaType("*", "*");
}

Install with Tessl CLI

npx tessl i tessl/maven-javax-ws-rs--javax-ws-rs-api

docs

client-api.md

core-types.md

extensions.md

index.md

resource-endpoints.md

server-container.md

server-sent-events.md

tile.json