Skip to lesson

Returning 201 Created with a Location header

After a staff member adds a product, the app needs to open its page. Only the server knows the new id, so the response must say where the new product lives.

Why a create returns 201 and where to find the new resource

201 Created is the status that says a new resource now exists. The Location header carries its URL, and the ShopLite contract also puts the created item in the body.

A create is a POST to a collection, and the server picks the new id. The example answers a create with 201 and a Location header.

Example 1 · A create answered with 201 and Location

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
Sample output
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:30:50 GMT

{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}

What this code does

  • All three parts of the contract's create answer: status 201, Location with the absolute URL of product 16, and the product itself in the body.
  • This is the same exchange the ShopLite API contract shows for "Create a product". Example 2 shows the code that produces it.

A plain 200 would say only "the request worked". The client could not tell a create from an update without reading the body, and it would have to guess the new URL from the id, which breaks the day URLs change. HTTP made 201 and Location for exactly this job.

The contract asks for all three parts on every create: status 201, the Location header and the created item in the body. The body saves the client a second request just to see the new id and defaults such as isActive: true.

Building the URI with ServletUriComponentsBuilder

ServletUriComponentsBuilder.fromCurrentRequest() starts a URI from the full URL of the request being handled: scheme, host, port and path. .path("/{id}") adds a part, .buildAndExpand(16) fills it in, and .toUri() gives a java.net.URI.

The controller must write the URL of the new product without hard-coding a host or a port. The example builds it from the current request.

Example 2 · The create method with ServletUriComponentsBuilder

Runs in: the rest-lab practice project (Spring Boot 4.1)

Java
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<ProductResponse> create(@RequestBody CreateProductRequest request) {    ProductResponse created = productService.create(request);    URI location = ServletUriComponentsBuilder.fromCurrentRequest()   // http://localhost:8080/api/v1/products            .path("/{id}")            .buildAndExpand(created.id())            .toUri();    return ResponseEntity.created(location).body(created);}
Output
(the response is the one in Example 1)

What this code does

  • fromCurrentRequest() gives http://localhost:8080/api/v1/products, the URL this POST came to; .path("/{id}") and .buildAndExpand(16) add /16.
  • The comments show the URL after each step. The id comes from the ProductResponse the service returned.
  • ResponseEntity.created(location) sets both the 201 status and the header, so the method no longer needs @ResponseStatus.

Starting from the current request means the header is always right for where the app actually runs: another port, another host name or a context path all appear without code changes. It also works for nested collections: a POST to /api/v1/customers/8/addresses gives .../customers/8/addresses/10.

The class lives in org.springframework.web.servlet.support, part of Spring Web MVC. It reads the current request from the thread, so call it inside the controller method, never in a service or a background thread.

ResponseEntity.created(uri).body(response)

ResponseEntity.created(uri) starts a response with status 201 and sets the Location header to uri. .body(created) then adds the new resource.

The earlier @ResponseStatus(HttpStatus.CREATED) can set the status but not a header. The example switches the create method to ResponseEntity.created.

Example 3 · AddressController.java: a nested create, and a missing parent

Runs in: the rest-lab practice project (Spring Boot 4.1)

AddressController.javaJava
package com.shoplite.lab.customer;
import java.net.URI;
import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController@RequestMapping("/api/v1/customers/{customerId}/addresses")public class AddressController {
    private final AddressService addressService;
    public AddressController(AddressService addressService) {        this.addressService = addressService;    }
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)    public ResponseEntity<AddressResponse> add(@PathVariable long customerId,                                               @RequestBody CreateAddressRequest request) {        return addressService.add(customerId, request)                .map(created -> {                    URI location = ServletUriComponentsBuilder.fromCurrentRequest()                            .path("/{id}")                            .buildAndExpand(created.id())                            .toUri();                    return ResponseEntity.created(location).body(created);                })                .orElseGet(() -> ResponseEntity.notFound().build());   // customer does not exist    }
    @GetMapping("/{addressId}")    public ResponseEntity<AddressResponse> get(@PathVariable long customerId, @PathVariable long addressId) {        return ResponseEntity.of(addressService.find(customerId, addressId));    }}
package com.shoplite.lab.customer;
import java.util.Map;import java.util.Optional;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
// Temporary in-memory store for the lab: seed customers 1 to 8, new address ids from 10@Servicepublic class AddressService {
    private static final Set<Long> CUSTOMER_IDS = Set.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L);
    private final Map<Long, AddressResponse> addresses = new ConcurrentHashMap<>();    private final AtomicLong nextId = new AtomicLong(10);
    // Empty when the customer does not exist    public Optional<AddressResponse> add(long customerId, CreateAddressRequest request) {        if (!CUSTOMER_IDS.contains(customerId)) {            return Optional.empty();        }        long id = nextId.getAndIncrement();        AddressResponse address = new AddressResponse(id, customerId,                request.label() == null ? "Home" : request.label(),                request.line1(), request.city(), request.state(), request.pincode(),                Boolean.TRUE.equals(request.isDefault()));        addresses.put(id, address);        return Optional.of(address);    }
    public Optional<AddressResponse> find(long customerId, long addressId) {        return Optional.ofNullable(addresses.get(addressId))                .filter(address -> address.customerId() == customerId);    }}
Sample output
$ curl -i -X POST http://localhost:8080/api/v1/customers/8/addresses -H "Content-Type: application/json" -d '{"label":"Home","line1":"4 Residency Road","city":"Bengaluru","state":"Karnataka","pincode":"560025","isDefault":true}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/customers/8/addresses/10
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:30:51 GMT

{"id":10,"customerId":8,"label":"Home","line1":"4 Residency Road","city":"Bengaluru","state":"Karnataka","pincode":"560025","isDefault":true}
$ curl -i -X POST http://localhost:8080/api/v1/customers/99/addresses -H "Content-Type: application/json" -d '{"line1":"1 Park Street","city":"Kolkata","state":"West Bengal","pincode":"700016"}'
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 05:30:52 GMT

What this code does

  • The same three builder calls give the nested URL .../customers/8/addresses/10, because the current request already contains /customers/8/addresses. This matches the contract's "Add an address" exchange.
  • The service returns an empty Optional for an unknown customer; the controller maps it to 404. The records CreateAddressRequest and AddressResponse have the contract's address fields, and a missing label becomes Home.
  • The map(...) lambda builds the URI only when something was created, so a 404 never carries a Location header.

The pieces stay in their layers. The service creates the product and returns its ProductResponse, including the new id. The controller builds the URI and the response, because URLs and headers are HTTP matters.

When the parent does not exist, as with a new address for customer 99, there is nothing to create and nothing to point at. The contract says 404, because the customer named in the URL is missing.

Order of execution

Order the create method

Put the steps of the create method in the order they run.

ProductResponse created = service.create(request);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(uri).body(created);

Seeing the header with curl -i, and getting it wrong

The X-Forwarded-* headers (X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port) are request headers that a proxy adds to tell the app which address the client really used. Spring reads them when server.forward-headers-strategy=framework is set.

curl -i shows the Location header, so a wrongly built URL shows up there. The examples print a correct header, then two wrong ones.

Example 4 · Two wrong ways to build Location

Runs in: the rest-lab practice project (Spring Boot 4.1)

Java
// Mistake 1: starts from the context path, so "/api/v1/products" is lost@PostMapping("/lab/location-mistakes/context-path")public ResponseEntity<ProductResponse> contextPath(@RequestBody CreateProductRequest request) {    ProductResponse created = productService.create(request);    URI location = ServletUriComponentsBuilder.fromCurrentContextPath()            .path("/{id}").buildAndExpand(created.id()).toUri();    return ResponseEntity.created(location).body(created);}
// Mistake 2: a hard-coded address that is only right on one computer and port@PostMapping("/lab/location-mistakes/hard-coded")public ResponseEntity<ProductResponse> hardCoded(@RequestBody CreateProductRequest request) {    ProductResponse created = productService.create(request);    URI location = URI.create("http://localhost:8080/api/v1/products/" + created.id());    return ResponseEntity.created(location).body(created);}
Sample output
$ curl -i -X POST http://localhost:8080/lab/location-mistakes/context-path ... (prints only the status and Location lines here)
HTTP/1.1 201
Location: http://localhost:8080/17

App started with --server.port=9090:
$ curl -i -X POST http://localhost:9090/lab/location-mistakes/hard-coded -H "Content-Type: application/json" -d '{"sku":"ACC-MS201","name":"Zebronics Mouse Pad","categoryId":4,"price":199.00}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:31:38 GMT

{"id":16,"sku":"ACC-MS201","name":"Zebronics Mouse Pad","categoryId":4,"categoryName":"Accessories","price":199.00,"stock":0,"isActive":true}

What this code does

  • fromCurrentContextPath() keeps only http://localhost:8080, so the header points to /17, a URL that answers 404.
  • The hard-coded version ran on port 9090 but still sent clients to port 8080, where nothing (or a different app) is listening. On a server it would point at localhost, the client's own computer.
  • Both compile and both answer 201, so only a check of the header with curl -i (or a test, next lesson) catches them.

Two mistakes are common. fromCurrentContextPath() starts from the application root, so /api/v1/products is lost and the header says http://localhost:8080/17. A hard-coded "http://localhost:8080/api/v1/products/" + id is right on one laptop and wrong everywhere else: started on port 9090, the app still points clients at 8080.

Behind a proxy or load balancer, the app sees the proxy's request, not the client's: the client calls https://api.shoplite.in, but the header says http://localhost:8080. Turn the forward-headers setting on only behind a proxy you trust, because a client could send those headers too.

How clients use the Location header

The Location header holds the absolute URL of the resource that was just created. A client follows it with a GET, instead of building the URL from the id.

A client follows Location by sending a GET to it. The examples follow the header from bash and from Java.

Example 5 · Following Location from bash, and behind a proxy

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
LOCATION=$(curl -s -o /dev/null -w '%header{location}' -X POST http://localhost:8080/api/v1/products --json '{"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"price":399.00,"stock":50}')echo "LOCATION=$LOCATION"curl "$LOCATION"# App started with --server.port=9090 --server.forward-headers-strategy=frameworkcurl -i -X POST http://localhost:9090/api/v1/products -H "Content-Type: application/json" -H "X-Forwarded-Proto: https" -H "X-Forwarded-Host: api.shoplite.in" -H "X-Forwarded-Port: 443" -d '{"sku":"FSH-CAP2","name":"Cotton Cap","categoryId":6,"price":299.00}'
Sample output
LOCATION=http://localhost:8080/api/v1/products/19
{"id":19,"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"categoryName":"Books","price":399.00,"stock":50,"isActive":true}

(second command, only the Location line)
Location: https://api.shoplite.in/api/v1/products/17

What this code does

  • -o /dev/null throws the body away and -w '%header{location}' prints the Location header, so the shell variable holds the new URL. The GET reads product 19 back without the script knowing its id.
  • With the forwarded-headers setting, the same builder code produced the public https://api.shoplite.in/... URL that the proxy's client used. Without the setting, Spring ignores those headers and writes http://localhost:8080/....
  • Your ids depend on how many products you created before.

Example 6 · FollowLocationDemo.java: Java HttpClient follows Location

Runs in: a JDK program, with the rest-lab project running on port 8080

FollowLocationDemo.javaJava
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;
public class FollowLocationDemo {
    private static final String BASE = "http://localhost:8080";
    public static void main(String[] args) throws Exception {        HttpClient client = HttpClient.newHttpClient();
        String json = """                {"sku":"BK-PRAG","name":"The Pragmatic Programmer","categoryId":5,"price":650.00,"stock":22}""";        HttpRequest create = HttpRequest.newBuilder(URI.create(BASE + "/api/v1/products"))                .header("Content-Type", "application/json")                .POST(HttpRequest.BodyPublishers.ofString(json))                .build();        HttpResponse<String> created = client.send(create, HttpResponse.BodyHandlers.ofString());        System.out.println("POST status: " + created.statusCode());
        // The server says where the new product lives; the client does not build the URL itself        String location = created.headers().firstValue("Location").orElseThrow();        System.out.println("Location: " + location);
        HttpRequest read = HttpRequest.newBuilder(URI.create(location)).GET().build();        HttpResponse<String> product = client.send(read, HttpResponse.BodyHandlers.ofString());        System.out.println("GET status: " + product.statusCode());        System.out.println(product.body());    }}
Sample output
POST status: 201
Location: http://localhost:8080/api/v1/products/16
GET status: 200
{"id":16,"sku":"BK-PRAG","name":"The Pragmatic Programmer","categoryId":5,"categoryName":"Books","price":650.00,"stock":22,"isActive":true}

What this code does

  • A plain JDK program (the Calling APIs from Java lesson showed HttpClient). Run it while the lab is running; on a fresh lab the new product is 16.
  • created.headers().firstValue("Location") returns an Optional<String>; orElseThrow() fails loudly if a server forgot the header.
  • The second request goes to exactly the URL the server gave. The client never pastes "/api/v1/products/" + id together.

That keeps working if the URL scheme changes, for example a new version path. Note that curl -L does not help here: it follows redirects (3xx), and 201 is not a redirect.

Typical uses: an admin app saves a product and opens its edit page from Location; a test creates a customer and then reads it back to check what was stored; a script stores the URL to update the item later. In bash, -w '%header{location}' prints one response header (curl 7.84 or later). In Java, HttpClient returns the headers and headers().firstValue("Location") gives the URL as an Optional.

Next step

Check your understanding

12 quick questions