REST API Best Practices
Learn clean REST API design patterns for versioning, idempotency, pagination, and error handling so clients can build on stable contracts.
Standard 1 — Design around resources, not actions
Rule: URLs identify things (plural nouns). HTTP methods define the operations performed on those things. Avoid RPC-style verbs in paths (/getUser, /createOrder).
Bad:
POST /createUser
GET /getUserById?id=42
POST /deleteUser
Good (Spring 4):
@RestController
@RequestMapping("/users")
public class UserController {
// GET /users -> list
@RequestMapping(method = RequestMethod.GET)
public List<User> list() {
return userService.findAll();
}
// GET /users/42 -> single resource
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User get(@PathVariable("id") Long id) {
return userService.findById(id);
}
// POST /users -> create
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<User> create(@RequestBody User user) {
User created = userService.create(user);
return ResponseEntity
.created(URI.create("/users/" + created.getId()))
.body(created);
}
// DELETE /users/42 -> remove
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> delete(@PathVariable("id") Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}
Standard 2 — Make URLs predictable
Rule: Use one consistent convention everywhere (plural nouns, lowercase, hyphens for multi-word segments, identifier-based sub-paths). A client should be able to guess the next endpoint.
Convention example:
/orders
/orders/42
/orders/42/items
/orders/42/items/7
/customers/42/orders
Spring 4:
@RestController
@RequestMapping("/orders")
public class OrderController {
@RequestMapping(value = "/{orderId}", method = RequestMethod.GET)
public Order getOrder(@PathVariable Long orderId) { ... }
// Consistent nesting: /orders/{orderId}/items
@RequestMapping(value = "/{orderId}/items", method = RequestMethod.GET)
public List<Item> listItems(@PathVariable Long orderId) { ... }
@RequestMapping(value = "/{orderId}/items/{itemId}", method = RequestMethod.GET)
public Item getItem(@PathVariable Long orderId,
@PathVariable Long itemId) { ... }
}
Don’t mix
/orders/{id}/itemswith/order-items?order=42in the same API.
Standard 3 — Use HTTP methods correctly & enforce idempotency
Rule: Respect HTTP semantics:
| Method | Purpose | Safe? | Idempotent? |
|---|---|---|---|
| GET | Retrieve | ✅ | ✅ |
| POST | Create (non-idempotent) | ❌ | ❌ |
| PUT | Full replace | ❌ | ✅ |
| PATCH | Partial update | ❌ | ❌ (usually) |
| DELETE | Remove | ❌ | ✅ |
Key insight: Calling GET, PUT, or DELETE N times must leave the system in the same state as calling it once.
Spring 4:
@RestController
@RequestMapping("/users")
public class UserController {
// GET is safe & idempotent
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User get(@PathVariable Long id) {
return userService.findById(id); // read-only, no side effects
}
// PUT = full replacement, idempotent
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public User replace(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.replace(user); // same result every time
}
// PATCH = partial update
@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
public User patch(@PathVariable Long id, @RequestBody Map<String, Object> patch) {
return userService.applyPatch(id, patch);
}
// DELETE idempotent: second call should still return 204 (or 404, but not 500)
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.deleteIfExists(id);
return ResponseEntity.noContent().build();
}
}
Spring 4 annotation shortcuts (cleaner but equivalent): @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping (available since Spring 4.3).
Standard 4 — Make status codes useful
Rule: Never return 200 OK for an error. Use the correct class:
- 2xx success (
200,201created,204no content) - 3xx redirect
- 4xx client error (
400bad request,401unauthenticated,403forbidden,404not found,409conflict,422validation,429rate limited) - 5xx server error
Spring 4:
@RestController
@RequestMapping("/users")
public class UserController {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(@RequestBody @Valid User user,
BindingResult binding) {
if (binding.hasErrors()) {
// 422 for validation failures
return ResponseEntity
.status(422)
.body(errorBody("VALIDATION_FAILED", binding));
}
User created = userService.create(user);
return ResponseEntity.status(201).body(created); // 201 Created
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(@PathVariable Long id) {
User user = userService.findById(id);
if (user == null) {
return ResponseEntity.status(404).build(); // 404 Not Found
}
return ResponseEntity.ok(user); // 200 OK
}
}
Standard 5 — Keep error responses consistent (structured error payloads)
Rule: All errors — from any endpoint — should share one JSON shape containing an application error code and a human-readable message. Clients can then react programmatically.
Standard error shape:
{
"code": "USER_NOT_FOUND",
"message": "User 42 does not exist",
"timestamp": "2024-05-01T12:34:56Z",
"path": "/users/42"
}
Spring 4 — centralize with @ControllerAdvice:
public class ApiError {
private String code;
private String message;
private String timestamp;
private String path;
// getters/setters
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ApiError> handleNotFound(UserNotFoundException ex,
HttpServletRequest req) {
return ResponseEntity.status(404)
.body(build("USER_NOT_FOUND", ex.getMessage(), req));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex,
HttpServletRequest req) {
return ResponseEntity.status(422)
.body(build("VALIDATION_FAILED", ex.getMessage(), req));
}
private ApiError build(String code, String msg, HttpServletRequest req) {
ApiError e = new ApiError();
e.setCode(code);
e.setMessage(msg);
e.setTimestamp(Instant.now().toString());
e.setPath(req.getRequestURI());
return e;
}
}
Even your controller-level
try/catchshould produce this same shape — never leak stack traces or{"error": "..."}variants.
Standard 6 — Paths identify resources; query parameters refine them
Rule: The path is the resource hierarchy. Query parameters handle filtering, sorting, pagination, and optional criteria. Don’t cram filters into the path.
Bad:
/orders/status/shipped/region/eu/page/2/sort/date
Good:
/orders?status=shipped®ion=eu&page=2&size=20&sort=createdAt,desc
Spring 4:
@RestController
@RequestMapping("/orders")
public class OrderController {
@RequestMapping(method = RequestMethod.GET)
public Page<Order> search(
@RequestParam(value = "status", required = false) String status,
@RequestParam(value = "region", required = false) String region,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "20") int size,
@RequestParam(value = "sort", defaultValue = "createdAt,desc") String sort) {
return orderService.search(status, region, page, size, sort);
}
}
Filtering never changes resource identity:
/orders/42is always order 42, regardless of query params.
Standard 7 — Treat API changes and versions carefully
Rule: Never break existing clients. Evolve APIs with explicit versioning (URI path /v1/..., custom media type, or header). Prefer additive, backward-compatible changes (new optional fields, new endpoints) over removals/renames.
Spring 4:
@RestController
@RequestMapping("/v1/users") // explicit version in path
public class UserControllerV1 {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public UserV1 get(@PathVariable Long id) { ... }
}
@RestController
@RequestMapping("/v2/users") // breaking change goes in a new version
public class UserControllerV2 {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public UserV2 get(@PathVariable Long id) { ... }
}
Alternative — header/media-type versioning (also Spring 4):
@RequestMapping(
value = "/users/{id}",
method = RequestMethod.GET,
produces = "application/vnd.myapp.v2+json"
)
public UserV2 getV2(@PathVariable Long id) { ... }
Backward-compatibility checklist:
- Adding a field → ✅ safe
- Adding an optional request param → ✅ safe
- Renaming/removing a field → ❌ breaking → needs new version
- Changing a status code or error
code→ ❌ breaking
Standard 8 — Keep formats consistent (global contracts)
Rule: Standardize across every endpoint:
- Property naming:
camelCase(orsnake_case) — pick one - Dates/timestamps: ISO 8601 (
2024-05-01T12:34:56Z) - IDs: consistent type
- Envelopes/pagination: one shape everywhere
Spring 4 — enforce at the Jackson level:
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// ISO 8601, no timestamps-as-numbers
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JavaTimeModule());
// camelCase property names
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE);
// Fail on unknown props (or configure to ignore, but do it globally)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
}
Consistent pagination envelope:
public class PageResponse<T> {
private List<T> items;
private int page;
private int size;
private long total;
// getters/setters
}
{
"items": [ ... ],
"page": 0,
"size": 20,
"total": 137
}
Every list endpoint returns this same envelope — clients never have to special-case a response.
Summary table
| # | Standard | One-line rule | Spring 4 tool |
|---|---|---|---|
| 1 | Resources, not actions | Plural nouns + HTTP methods | @RestController, @RequestMapping |
| 2 | Predictable URLs | Consistent naming & nesting | @RequestMapping("/{id}") |
| 3 | Correct methods & idempotency | GET/PUT/DELETE repeatable | @GetMapping, @PutMapping, @DeleteMapping |
| 4 | Useful status codes | 201/204/400/404/422/429 | ResponseEntity.status(...) |
| 5 | Consistent errors | One JSON error shape | @ControllerAdvice + @ExceptionHandler |
| 6 | Paths vs. query params | Path = identity, query = refinement | @PathVariable vs @RequestParam |
| 7 | Careful versioning | /v1/, additive changes |
@RequestMapping("/v1/...") |
| 8 | Consistent formats | camelCase + ISO 8601 globally | ObjectMapper config |
These eight laws are the deduplicated core: the same eight principles were listed twice in the source file, so the two lists are merged here into one authoritative set with detailed Java Spring 4 illustrations.
Hands-on: Global ISO-8601 + camelCase Configuration in Spring 4
Spring 4’s ObjectMapper can be configured globally with a @Bean definition. The key is to register Java 8’s time module and disable timestamp serialization so dates come out as ISO-8601 strings, while setting the naming strategy to camelCase (which is usually the default, but making it explicit locks the contract).
Prerequisites (Maven dependencies)
Spring 4 does not pull in JSR-310 support automatically. You need the JavaTime module on the classpath:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.10</version> <!-- align with your Jackson core version -->
</dependency>
Spring 4.0+ has first-class support for java.time (JSR-310) , but Jackson still needs JavaTimeModule registered to serialize LocalDateTime, LocalDate, Instant, etc.
The Configuration Class
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 1. Register Java 8 date/time support
mapper.registerModule(new JavaTimeModule());
// 2. Force ISO-8601 strings instead of numeric timestamps
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 3. Lock in camelCase property naming globally
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
return mapper;
}
}
Why Each Line Matters
registerModule(new JavaTimeModule()) — Without this, Jackson treats LocalDateTime as an unknown type and either fails or serializes it as an object with year, month, day fields. The JavaTime module provides the correct serializer/deserializer .
disable(WRITE_DATES_AS_TIMESTAMPS) — By default, Jackson may serialize dates as epoch milliseconds (e.g., 1541152800000). Disabling this forces ISO-8601 output like 2018-11-21T11:13:13.274 . The exact output depends on the type:
LocalDate→2018-11-21LocalDateTime→2018-11-21T11:13:13.274ZonedDateTime→2018-11-21T11:13:13.274+01:00
setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) — Java fields are already camelCase by convention, and Jackson’s default is camelCase. Setting it explicitly prevents accidental drift (e.g., if someone later adds a global SnakeCase setting) and documents the contract. If your Java fields are snake_case but you want camelCase JSON, this strategy translates them.
Verification: What You Get
With the config above, a DTO like:
public class UserDto {
private String userName;
private LocalDateTime createdAt;
private LocalDate birthDate;
// getters/setters
}
Serializes to:
{
"userName": "alice",
"createdAt": "2024-05-01T12:34:56.789",
"birthDate": "1990-01-15"
}
No timestamps-as-numbers, no snake_case keys, no per-field @JsonFormat annotations needed.
Spring 4-Specific Caveat
Spring 4 uses Jackson 2.x. If you are on an older Jackson version (2.4–2.6), PropertyNamingStrategy.LOWER_CAMEL_CASE may not exist as a constant. In that case, the default behavior already produces camelCase, so you can omit that line or use PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES only if you actually want snake_case. For pure camelCase, simply not setting a strategy is equivalent and safe across all Jackson 2.x versions.
Common Pitfall: Spring MVC’s Message Converter
The @Bean ObjectMapper above will be picked up by Spring MVC’s MappingJackson2HttpMessageConverter if you have @EnableWebMvc or XML <mvc:annotation-driven/> configured. If your controllers still serialize dates as timestamps, verify that:
- The config class is in a package scanned by Spring.
- No other
ObjectMapperbean is overriding it. - The message converter hasn’t been manually configured with a different mapper.
In Spring 4, the most reliable approach is to expose the ObjectMapper as a bean and let Spring’s auto-configuration wire it into the converter. The manual @Bean approach shown above works consistently when the bean is the only ObjectMapper in the context.
Subscribe & Follow
Get notified of new technical articles on AI/ML, Java, Python, and system architecture.