Post

Fill Path Parameters in REST Assured

Fill the placeholders of a path with named and unnamed parameters, mix the two, see how values are URL-encoded, and find a real resource through its Location header.

Fill Path Parameters in REST Assured

Your payment tests build every URL with "/payments/" + id. It works until a test passes a beneficiary name with a space in it, and the failure doesn’t tell you which URL was really sent. In this guide, you’ll write each path as a template such as /payments/{id}, fill its placeholders with path parameters, and check on the wire exactly what REST Assured sent.

Level: Beginner · Time: 20 minutes · Part of: Module 2: Building Requests, section 1

What You’ll Build

You’ll build a test class called PathParametersTest with six tests. Five send requests to an echo endpoint that describes the request it received, so each test can prove what REST Assured put in the path. The sixth creates a payment and reads it back by its id.

One of the tests sends this request and checks this response:

1
2
3
4
5
6
7
GET /api/v1/echo/Anna%20de%20Vries HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"method":"GET","path":"/api/v1/echo/Anna de Vries","rawPath":"/api/v1/echo/Anna%20de%20Vries", ...}

When you’re done, Maven reports six passing tests:

1
2
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Fill named path parameters.
  • Fill unnamed path parameters by position.
  • Check how values are URL-encoded.
  • Request a real resource by its id.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: this is the first section of Module 2, so you start from scratch. Create PathParametersTest in the module-02 test sources and follow every heading below.
  • Skip ahead: open the finished class (PathParametersTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: clone the examples repository and change into it:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples

If you’ve already cloned it for Module 1, run git pull instead.

Out of scope: this guide doesn’t explain the request headers and body that create a payment, or extract(), which the last test uses. They’re taught in Module 2, section 3, section 4 and Module 4.

Understand Path Parameters

The problem. Building a path with + mixes the fixed part of a URL with the values that change. The value goes into the URL unencoded, so a space or a slash breaks the request. And the path no longer reads as a template, so you can’t search the code base for /payments/{id}.

The concept. A path parameter is a value that fills a {placeholder} in the path. REST Assured has two ways to supply it:

  • Named, with pathParam("id", "pay-42") or pathParams(map) on the request. The name must match the placeholder.
  • Unnamed, as extra arguments to the method that sends the request, as in get("/payments/{id}", "pay-42"). The values fill the placeholders in order, and the names in the path don’t matter.

You can mix the two in one request. Named values are filled first, and the unnamed values fill the placeholders still open, from left to right. Either way, REST Assured URL-encodes every value.

When to use each. Use unnamed values when the order is obvious, such as a single id. Use named values when a path has several placeholders, or when a helper sets the parts that never change and each test supplies the rest. Use concatenation never: it gives up encoding and readability for nothing.

Write the path as a template, and let REST Assured fill and encode the values.

Meet the API Under Test

Module 2 tests a Payments API. It runs on the JDK’s built-in HTTP server, like the Accounts API of Module 1, starts on a free port and serves its endpoints under /api/v1. This guide uses three of them:

MethodPathPurpose
Any/echo, /echo/{a}, /echo/{a}/{b}Describe the request as the server received it
POST/paymentsCreate a payment
GET/payments/{id}Fetch one payment

Most tests in this module use the echo endpoints. A request to /api/v1/echo/Anna%20de%20Vries returns a response similar to the following, shortened:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{
    "method": "GET",
    "path": "/api/v1/echo/Anna de Vries",
    "rawPath": "/api/v1/echo/Anna%20de%20Vries",
    "rawQuery": "",
    "query": {},
    "headers": { "accept": ["*/*"], ... },
    "cookies": {},
    "contentType": "",
    "bodyLength": 0,
    "body": ""
}

Creating a payment returns 201 Created with a Location header that holds the new payment’s URL:

1
2
3
4
5
6
7
8
9
10
11
12
HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8
Location: /api/v1/payments/pay-1

{
    "id": "pay-1",
    "status": "RECEIVED",
    "creditorName": "Jan Jansen",
    "amount": "10.00",
    "currency": "EUR",
    ...
}

Your tests check three things:

  • The echo’s path field, the path after the server decoded it.
  • The echo’s rawPath field, the path exactly as it was on the wire. Comparing it with path shows what REST Assured encoded.
  • The payment’s id, which the last test reads from the Location header and sends back as a path parameter.

Fill Named Path Parameters

Set Up the Test Class

Goal: create the test class, start the Payments API and add a shared request helper.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.javanibble.module_02.section_01;

import static com.javanibble.module_02.support.SamplePayments.validPaymentJson;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import com.javanibble.payments.PaymentsApi;

import io.restassured.specification.RequestSpecification;

import java.util.Map;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class PathParametersTest {

    private static PaymentsApi api;

    @BeforeAll
    static void startApi() {
        api = PaymentsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification paymentsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(PaymentsApi.BASE_PATH);
    }
}

What’s happening:

  • PaymentsApi is Module 2’s test server. It starts and stops the same way as the Accounts API in Module 1.
  • paymentsApi() returns a request with the base URI, port and base path /api/v1 set, like the accountsApi() helper you’ve used before.
  • validPaymentJson(..) comes from the module’s SamplePayments helper. It builds a valid payment body for the last test.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Fill One Named Parameter

Goal: fill a placeholder by name.

1
2
3
4
5
6
7
8
9
@Test
void namedPathParameter() {
    paymentsApi()
        .pathParam("id", "pay-42")
    .when()
        .get("/echo/{id}")
    .then()
        .body("path", equalTo("/api/v1/echo/pay-42"));
}

What’s happening:

  • pathParam("id", "pay-42") stores a value for the placeholder called id on the request.
  • get("/echo/{id}") keeps the path as a template that reads clearly and that you can search for.
  • The echo’s path field proves the request went to /api/v1/echo/pay-42.

Checkpoint: run PathParametersTest from your IDE. One test runs and passes.

A misspelled name doesn’t fill the placeholder. With pathParam("ID", ..), REST Assured refuses to send the request and throws IllegalArgumentException: Path parameters were not correctly defined. Redundant path parameters are: ID=pay-42. Undefined path parameters are: id.

Fill Several Named Parameters From a Map

Goal: fill two placeholders at once.

1
2
3
4
5
6
7
8
9
@Test
void severalNamedPathParametersFromAMap() {
    paymentsApi()
        .pathParams(Map.of("resource", "payments", "id", "pay-42"))
    .when()
        .get("/echo/{resource}/{id}")
    .then()
        .body("path", equalTo("/api/v1/echo/payments/pay-42"));
}

What’s happening:

  • pathParams(..) takes a map from placeholder names to values.
  • Every value has a name, so the order of the map doesn’t matter. Map.of(..) has no fixed order, and the test still passes.

Checkpoint: run the class again. Two tests pass.

Fill Unnamed Path Parameters by Position

Fill the Placeholders in Order

Goal: fill two placeholders from the extra arguments of get(..).

1
2
3
4
5
6
7
8
@Test
void unnamedPathParametersAreFilledInOrder() {
    paymentsApi()
    .when()
        .get("/echo/{resource}/{id}", "payments", "pay-42")
    .then()
        .body("path", equalTo("/api/v1/echo/payments/pay-42"));
}

What’s happening:

  • The first value fills the first placeholder, and the second value the second.
  • The names {resource} and {id} don’t matter here; only the order counts.
  • This is the shortest form, and the one you’ll see most.

Checkpoint: run the class again. Three tests pass.

Mix Named and Unnamed Values

Goal: fill one placeholder by name and the other by position.

1
2
3
4
5
6
7
8
9
@Test
void namedAndUnnamedCanBeMixed() {
    paymentsApi()
        .pathParam("resource", "payments")
    .when()
        .get("/echo/{resource}/{id}", "pay-42")
    .then()
        .body("path", equalTo("/api/v1/echo/payments/pay-42"));
}

What’s happening:

  • pathParam("resource", "payments") fills {resource} first.
  • The only unnamed value, "pay-42", goes to {id}, the first placeholder still open.
  • This is useful when a helper sets the parts of the path that never change, and each test supplies the id.

Checkpoint: run the class again. Four tests pass.

Check How Values Are URL-Encoded

Send a Value With Spaces

Goal: prove that REST Assured encodes a value before sending it, and that the server decodes it back.

A path can’t contain a space, so REST Assured encodes every path parameter value:

1
2
3
4
5
6
7
8
9
@Test
void valuesAreUrlEncoded() {
    paymentsApi()
    .when()
        .get("/echo/{name}", "Anna de Vries")
    .then()
        .body("rawPath", equalTo("/api/v1/echo/Anna%20de%20Vries"))
        .body("path", equalTo("/api/v1/echo/Anna de Vries"));
}

What’s happening:

  • rawPath proves that each space travelled as %20.
  • path proves that the server decoded it back to the original value.
  • A slash in a value is encoded too, as %2F, so "a/b" stays one path segment on the wire instead of becoming two.

Checkpoint: run the class again. Five tests pass.

Pass the plain value and let REST Assured encode it. If you encode it yourself, it’s encoded twice: "Anna%20de%20Vries" goes on the wire as Anna%2520de%2520Vries, because the % is encoded as %25. Section 2 shows how to turn encoding off when you need to.

Request a Real Resource by Its Id

The echo endpoints show what was sent. The last test uses a real resource: it creates a payment, then reads it back by the id the API gave it.

Create a Payment and Read It Back

Goal: take a generated id from the Location header and use it as a path parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
void aRealResource() {
    String location = paymentsApi()
        .header("X-Request-ID", "path-params-1")
        .contentType("application/json")
        .body(validPaymentJson("10.00"))
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .extract().header("Location");

    String id = location.substring(location.lastIndexOf('/') + 1);

    paymentsApi()
    .when()
        .get("/payments/{id}", id)
    .then()
        .statusCode(200)
        .body("id", equalTo(id));
}

What’s happening:

  • The first chain sends POST /payments with a request id header and a JSON body, and checks for 201 Created. Headers and bodies are the topics of sections 3 and 4.
  • extract().header("Location") returns the header’s value, such as /api/v1/payments/pay-1, instead of checking it. Module 4 covers extract().
  • substring(..) takes the id from the end of the location.
  • The second chain sends the id as a path parameter, and checks that the payment it gets back has the same id.

Checkpoint: run the class again. All six tests pass.

Don’t hard-code ids the server generates, such as pay-1. They come from a counter, so they depend on how many payments other tests created first. Read the id from the response, as this test does.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-02 -Dtest=PathParametersTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_02.section_01.PathParametersTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.430 s -- in com.javanibble.module_02.section_01.PathParametersTest
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In unnamedPathParametersAreFilledInOrder, swap the two values so the call reads get("/echo/{resource}/{id}", "pay-42", "payments"), and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   PathParametersTest.unnamedPathParametersAreFilledInOrder:67 1 expectation failed.
JSON path path doesn't match.
Expected: /api/v1/echo/payments/pay-42
  Actual: /api/v1/echo/pay-42/payments

The request was sent without complaint, because unnamed values only fill placeholders by position. The echo’s path field shows the swap straight away, which is why the echo endpoints are useful for request-building tests.

Swap the values back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
IllegalArgumentException: Path parameters were not correctly defined. ... Undefined path parameters are: id.The name in pathParam(..) doesn’t match the placeholderUse the exact placeholder name; names are case-sensitive
IllegalArgumentException: Invalid number of path parameters. Expected 1, was 2.More unnamed values than placeholdersPass one value per open placeholder
rawPath shows %2520 instead of %20The value was encoded before it was passed inPass the plain value
404 with Payment pay-1 does not existThe test hard-codes a generated idRead the id from the Location header

Try It Yourself

Exercise 1: Encode a Named Value

Add a test called namedValuesAreUrlEncodedToo that fills a placeholder called name with "Jan Jansen" using pathParam(..), requests /echo/{name}, and checks both rawPath and path.

Hint

Combine namedPathParameter with the two checks from valuesAreUrlEncoded. Encoding works the same way for named and unnamed values.

Solution
1
2
3
4
5
6
7
8
9
10
@Test
void namedValuesAreUrlEncodedToo() {
    paymentsApi()
        .pathParam("name", "Jan Jansen")
    .when()
        .get("/echo/{name}")
    .then()
        .body("rawPath", equalTo("/api/v1/echo/Jan%20Jansen"))
        .body("path", equalTo("/api/v1/echo/Jan Jansen"));
}

Exercise 2: Read a New Payment With a Named Parameter

Add a test called aNewPaymentCanBeReadByName that creates a payment with an amount of "25.50" and the request id path-params-2. Read it back with pathParam("id", ..) instead of an unnamed value, and check the status code, the id and the amount.

Hint

Start from aRealResource. In the second chain, move the id into pathParam(..) before when(). The API returns amount as a string, so compare it with "25.50".

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
void aNewPaymentCanBeReadByName() {
    String location = paymentsApi()
        .header("X-Request-ID", "path-params-2")
        .contentType("application/json")
        .body(validPaymentJson("25.50"))
    .when()
        .post("/payments")
    .then()
        .statusCode(201)
        .extract().header("Location");

    String id = location.substring(location.lastIndexOf('/') + 1);

    paymentsApi()
        .pathParam("id", id)
    .when()
        .get("/payments/{id}")
    .then()
        .statusCode(200)
        .body("id", equalTo(id))
        .body("amount", equalTo("25.50"));
}

Summary

You built PathParametersTest, which fills path placeholders by name, by position and both at once, proves how values are encoded, and reads a payment by its generated id. No URL in your tests needs + any more.

  • A path parameter fills a {placeholder} in a path template.
  • Named values come from pathParam(..) or pathParams(..), and their names must match the placeholders exactly.
  • Unnamed values come from the extra arguments of get(..) and fill the placeholders in order; mixed with named values, they fill the placeholders still open.
  • REST Assured URL-encodes every value, so pass it plain; the echo endpoint’s rawPath shows what went over the wire.
  • Read generated ids from the response instead of hard-coding them.

Here are the commands you used in this guide:

1
2
3
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
mvn test -pl module-02 -Dtest=PathParametersTest

What’s Next

Next: continue with Send Query and Form Parameters in REST Assured, which puts values in the query string and the form body, and shows how to turn URL encoding off.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.