Java REST API Interview Questions
This section covers common interview questions related to Java REST APIs, focusing on core concepts, HTTP methods, and best practices.
What is a RESTful API?
A RESTful API (Representational State Transfer Application Programming Interface) is an architectural style for building web services. It uses HTTP methods (GET, POST, PUT, DELETE) to interact with resources identified by URLs. Key characteristics include statelessness, a uniform interface, and the use of standard HTTP status codes.
Main Components of a RESTful API
- Resources: Data or objects the API manages (identified by URLs).
- HTTP Methods:
GET
(retrieve),POST
(create),PUT
(update),DELETE
(delete). - URIs (Uniform Resource Identifiers): Unique URLs for resources.
- Representations: Data formats (JSON, XML, etc.).
- Statelessness: Each request is independent; the server doesn't store client context between requests.
PUT
vs. POST
Methods
PUT
: Updates an existing resource or creates it if it doesn't exist. The entire resource representation is sent in the request body.POST
: Creates a new resource. The new resource's ID is typically generated by the server.
Content Negotiation
Content negotiation determines the best response format (JSON, XML, etc.) based on the client's request (usually using the Accept
header).
HTTP Status Codes
HTTP status codes communicate the result of a request:
- 2xx (Success):
200 OK
,201 Created
,204 No Content
- 4xx (Client Error):
400 Bad Request
,401 Unauthorized
,404 Not Found
- 5xx (Server Error):
500 Internal Server Error
OPTIONS
Method
The OPTIONS
method retrieves the communication options (supported HTTP methods, headers, etc.) for a resource.
Query Parameters
Query parameters are added to a URL to filter or modify requests (e.g., /users?name=John&age=30
).
HATEOAS (Hypermedia as the Engine of Application State)
HATEOAS is a REST architectural constraint. It promotes including hyperlinks in API responses to allow clients to discover and navigate related resources dynamically.
API Versioning
Versioning helps maintain backward compatibility when updating APIs. Common approaches include:
- URI versioning (e.g.,
/v1/users
,/v2/users
) - Custom headers (e.g.,
X-API-Version
) - Content negotiation (using the
Accept
header)
Authentication and Authorization
- Authentication: Verifying the client's identity (API keys, OAuth, etc.).
- Authorization: Determining what actions a client is allowed to perform.
Exception Handling in Java REST APIs
Handle exceptions using try-catch
blocks and return appropriate HTTP status codes and error messages. Exception mappers (using the @Provider
annotation and ExceptionMapper
interface) can customize error responses.
@PathParam
Annotation (JAX-RS)
The @PathParam
annotation extracts values from the URI path.
Example: @PathParam
@GET
@Path("/{userId}")
public Response getUser(@PathParam("userId") int userId) { ... }
@Consumes
and @Produces
Annotations (JAX-RS)
@Consumes
: Specifies the media types a resource accepts (e.g.,@Consumes("application/json")
).@Produces
: Specifies the media types a resource returns (e.g.,@Produces("application/json")
).
Securing a Java REST API
Security measures for Java REST APIs include:
- Token-based authentication (JWT).
- OAuth 2.0.
- Basic authentication (with HTTPS).
- Role-Based Access Control (RBAC).
Pagination in Java REST APIs
Pagination manages large result sets by returning data in smaller chunks (pages). Use query parameters (like page
and pageSize
) to specify the page number and number of items per page.
Example: Pagination
@GET
@Path("/users")
public Response getUsers(@QueryParam("page") int page, @QueryParam("pageSize") int pageSize) { ... }
@QueryParam
Annotation (JAX-RS)
The @QueryParam
annotation extracts values from query parameters in the URI. This allows you to retrieve data passed in the query string.
Example: @QueryParam
@GET
@Path("/users")
public Response getUsers(@QueryParam("filter") String filter) {
// Use the 'filter' parameter here...
}
@HeaderParam
Annotation (JAX-RS)
The @HeaderParam
annotation retrieves values from HTTP request headers. This is commonly used to access authentication tokens or other metadata sent in the request.
Example: @HeaderParam
@GET
@Path("/resource")
public Response myMethod(@HeaderParam("Authorization") String authToken) {
// Use the 'authToken' here...
}
The Jackson Library
Jackson is a widely used Java library for JSON processing. In REST APIs, Jackson serializes (converts Java objects to JSON) for responses and deserializes (converts JSON to Java objects) for requests. Annotations like @JsonProperty
help customize this mapping.
Cross-Origin Resource Sharing (CORS)
CORS is a browser security mechanism restricting requests from web pages to different domains. To address CORS issues in a Java REST API, configure your server to send appropriate CORS headers (like Access-Control-Allow-Origin
, Access-Control-Allow-Methods
, etc.) in responses.
Example: CORS Filter (JAX-RS)
@Provider
public class CorsFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
responseContext.getHeaders().add("Access-Control-Allow-Headers", "Content-Type");
}
}
This example shows a simple CORS filter that allows requests from any origin. In a production environment, you would typically restrict this to specific allowed origins for enhanced security.