Post

Syllabus: REST Assured Learning Guide

REST Assured is a popular Java tool that makes testing web APIs simple and easy to read. This learning guide walks you through practical examples to show you how to send requests, check responses, and build reliable automated API tests.

Syllabus: REST Assured Learning Guide

How to Use This Guide

Each section links to a guide that explains the theory, introduces the API under test and walks through the REST Assured tests. The matching code is in the REST Assured Examples repository, so you can run the tests and change them as you read.

  • Beginner: start at Module 1 and work through in order.
  • Intermediate: start at Module 4.
  • Advanced: jump to the modules you need from Module 7 onwards.

Looking for one topic? Use the search box or scan the tables below.

Course Modules

Work through the modules in order. They build on each other conceptually, but their code is independent, so you can also run any module on its own. The code for every module is in the REST Assured Examples repository on GitHub.

ModuleLevelTopics
1. FoundationsBeginnergiven/when/then, where requests go, first assertions, logging, reading failures
2. Building requestsBeginnerParameters, headers, cookies, bodies, every HTTP method, multipart
3. Validating responses in depthBeginner to IntermediateGPath, root paths, money as BigDecimal, Hamcrest, cookies, XML and HTML
4. Extracting values and mapping objectsIntermediateextract(), JsonPath, records, TypeRef, Jackson 3, chaining
5. Reusable specifications and configurationIntermediateSpecifications, RestAssuredConfig, timeouts, redirects, log masking, a JUnit extension
6. Schema and contract validationIntermediateJSON Schema 2020-12, RFC 9457, ISO 20022 XSD, an OpenAPI contract filter
7. Authentication and transport securityIntermediate to AdvancedBasic, bearer, client credentials, negative security tests, sessions, mutual TLS, redirects
8. Filters and extensibilityAdvancedCustom filters, HTTP message signatures, log masking, custom authentication, parsers, listeners
9. Data-driven tests and API workflowsAdvancedParameterized and dynamic tests, workflows, idempotency, ETags, pagination, polling
10. Stubbing dependencies with WireMockAdvancedStubs, faults, verifying outgoing calls, templates, scenarios
11. Spring Boot integrationAdvancedRestAssuredMockMvc, Spring Security, random-port servers, version alignment
12. Real infrastructure with TestcontainersAdvancedKeycloak tokens, parallel execution, tags and profiles

Module 1: Foundations

How a REST Assured test is put together, where its requests go, how to check a response, and how to read what happens when a check fails. The tests run against an Accounts API. See the Module 1 README for the code and how to run it.

SectionGuideWhat you will learn
1Send Your First REST Assured RequestStart a real HTTP API with @BeforeAll, send a request with given/when/then, and check the status code and JSON body
2Take Apart a REST Assured TestThe three types behind given/when/then, the syntactic sugar, the shorter forms, stored responses and a first path parameter
3Control Where REST Assured Requests GoHow a URL is built from baseUri, port, basePath and the path, when an absolute URL wins, and why static defaults are global state
4Check Every Part of an HTTP ResponseStatus codes and lines, content types, case-insensitive headers, GPath body paths, lists, Float numbers, problem details and response time
5Log REST Assured Requests and ResponsesLogging everything, single parts, only when validation fails, only for errors, or only for one status code
6Read REST Assured Failure MessagesThe shape of a failure message, why a then() chain stops at its first failure, and how one body(..) call reports every mismatch

Module 1 Build Module 1: Build & Test Results

Module 2: Building Requests

Every way to put data into a request, and how to send every HTTP method. The tests run against a Payments API with echo endpoints that show exactly what was sent. See the Module 2 README for the code and how to run it.

SectionGuideWhat you will learn
1Fill Path Parameters in REST AssuredNamed and unnamed path parameters, mixing the two, URL encoding, and finding a resource through its Location header
2Send Query and Form Parameters in REST AssuredMulti-value and empty query parameters, java.time values, form bodies, turning URL encoding off, and where param(..) puts its value
3Send Headers and Cookies in REST AssuredHeaders from maps and objects, merging versus overwriting, accept(..), the charset added to text types, and cookies
4Send Request Bodies in REST AssuredWhich bodies are sent as they are and which are serialized, records as typed bodies, and testing 422 and 415 rejections
5Send Every HTTP Method in REST AssuredReplacing, patching and cancelling a resource, HEAD, OPTIONS, the new QUERY method, custom methods and 405
6Upload Files With Multipart Requests in REST AssuredUploading a file with a text field from a File, from bytes and with MultiPartSpecBuilder, and testing a missing part

Module 2 Build Module 2: Build & Test Results

Module 3: Validating Responses in Depth

How to check any part of a response precisely: GPath for JSON, root paths, numbers and money, the Hamcrest matchers you will use most, response-aware matchers, cookies and their security attributes, and XML and HTML. The tests run against a Transactions API with one account and a month of transactions. See the Module 3 README for the code and how to run it.

SectionGuideWhat you will learn
1Filter JSON Lists With GPath in REST AssuredFiltering and transforming lists with Groovy closures, any and every, max and min, ranges, flatten(), keys with dashes and a JSON array at the root
2Shorten JSON Paths With Root Paths in REST AssuredRemoving the repeated start of a path with rootPath(..), moving it during a chain, and reusing one path for many values with withArgs(..)
3Check Money Exactly With BigDecimal in REST AssuredHow JSON numbers are read, why Float can’t hold money, BigDecimal with JsonConfig, comparesEqualTo versus equalTo, exact sums and closeTo
4Pick the Right Hamcrest Matcher in REST AssuredThe difference between hasItems, contains and containsInAnyOrder, map and string matchers, and combining matchers with allOf, anyOf, oneOf and not
5Check Server-Generated Values With Response-Aware MatchersChecking values the server chooses, such as a new id in the Location header, with a lambda or endsWithPath(..), and one body value against another
6Check Session Cookie Security in REST AssuredChecking cookie values and the Secure, HttpOnly, SameSite, Path and Max-Age attributes of a session cookie, and reading a Cookie object
7Check XML and HTML Responses in REST AssuredXML paths and attributes, find and findAll on elements, depth-first search with **, namespaces with declareNamespace(..), and lenient HTML

Module 3 Build Module 3: Build & Test Results

Module 4: Extracting Values and Mapping Objects

How to get data out of responses, as single values or as Java records, how to configure the object mapper, and how to chain requests in which each step uses what the previous one returned. The tests run against a Customers and Consents API modelled on open banking account access consents. See the Module 4 README for the code and how to run it.

SectionGuideWhat you will learn
1Extract Values From a Response in REST AssuredExtracting a value, a list, headers and the whole response, using a value in the next request, and why you validate before you extract
2Read Many Values With JsonPath and XmlPath in REST AssuredTyped getters that convert values, maps and mapped objects, and reading JSON and XML that didn’t come from an HTTP call
3Map Responses to Java Records in REST AssuredMapping bodies to records with as(..), generic types with TypeRef, unknown fields in Jackson 3, and AssertJ assertions on records
4Configure the Object Mapper in REST AssuredChoosing a mapper with ObjectMapperType, the lenient default, a strict JsonMapper, and the 6.3 factory interfaces
5Chain Requests Into an API Flow in REST AssuredFollowing Location headers and _links, the full consent flow from customer to balances, and testing what a consent must refuse

Module 4 Build Module 4: Build & Test Results

Module 5: Reusable Specifications and Configuration

How to remove repetition from a suite and configure REST Assured safely: request and response specifications, RestAssuredConfig, keeping secrets out of logs, and a JUnit 6 extension that replaces static configuration. The tests run against an account information API in the style of the UK Open Banking standard. See the Module 5 README for the code and how to run it.

SectionGuideWhat you will learn
1Build Reusable Request Specifications in REST AssuredBuilding and layering request specifications, testing without credentials, overriding a header with HeaderConfig, and inspecting a specification
2Share Response Checks With Response Specifications in REST AssuredShared expectations for success and errors, then().spec(..) and given(request, response), and why a specification reports every failure at once
3Configure Timeouts, Redirects and Charsets in REST AssuredConnect and read timeouts with Duration, following redirects for GET, POST and all methods, and setting the default charset for decoding
4Keep Secrets Out of REST Assured LogsMasking Authorization and Cookie headers with blacklistHeader(..), masking when logging on failure, and testing what was logged
5Inject REST Assured Specifications With a JUnit ExtensionA JUnit 6 extension that starts the API per class, injects specifications as parameters, and closes the API through the extension store

Module 5 Build Module 5: Build & Test Results

Module 6: Schema and Contract Validation

How to check the shape of responses instead of single values: JSON Schema 2020-12, a shared contract for errors, XML Schema for ISO 20022 messages, and checking every response against an OpenAPI description. The tests run against a payment initiation API in the style of PSD2. See the Module 6 README for the code and how to run it.

SectionGuideWhat you will learn
1Validate Responses Against a JSON Schema in REST AssuredValidating whole responses against a draft 2020-12 schema, what a schema catches that value checks miss, inline schemas, and validating JSON without HTTP
2Test an RFC 9457 Error Contract in REST AssuredOne problem schema for every error, if/then/else so a 422 must list its field errors, and testing the schema itself
3Validate ISO 20022 XML Against an XSD in REST AssuredValidating payment files and status reports with matchesXsdInClasspath(..), checking test data, and handling the SAXParseException of an invalid document
4Check Every Response Against OpenAPI With a REST Assured FilterA filter that checks every operation, status and body against an OpenAPI 3.1 description, and the difference between contract and functional tests

Module 6 Build Module 6: Build & Test Results

Module 7: Authentication and Transport Security

How to test protected APIs, including everything that must happen when credentials are missing, wrong or not enough: Basic authentication, OAuth 2.0 bearer tokens, the error responses of RFC 6749 and RFC 6750, sessions with CSRF, TLS and mutual TLS, and credentials on redirects. The tests run against an OAuth 2.0 authorization server and the resource server it protects. See the Module 7 README for the code and how to run it.

SectionGuideWhat you will learn
1Test HTTP Basic Authentication in REST AssuredThe 401 challenge, challenged and preemptive Basic, why challenged Basic fails against a server that never challenges, and wrong credentials
2Get and Send OAuth 2.0 Bearer Tokens in REST AssuredGetting a token with the client credentials grant, client_secret_basic and client_secret_post, sending it with auth().oauth2(..), and reading JWT claims
3Write Negative Security Tests for OAuth 2.0 in REST AssuredToken endpoint errors, WWW-Authenticate responses for missing, expired, wrong-audience and tampered tokens, 401 versus 403, and a missing scope
4Test a Session Login With CSRF in REST AssuredReading a CSRF token with htmlPath(), keeping a session with a SessionFilter, setting the session id explicitly, and a missing or reused CSRF token
5Test HTTPS and Mutual TLS in REST AssuredWhy relaxedHTTPSValidation() is the wrong fix, trusting a certificate with a trust store, presenting a client certificate, and passing a JDK SSLContext
6Keep Credentials Off Cross-Origin Redirects in REST AssuredHow REST Assured 6.1 drops Authorization and Cookie on cross-origin redirects, testing what a redirect target receives, and the opt-out

Module 7 Build Module 7: Build & Test Results

Module 8: Filters and Extensibility

How to change every request and response in one place with filters, sign requests, mask personal data in logs, write a custom authentication scheme, read misbehaving responses with parsers, and react to failures with listeners. The tests run against a payments API that requires signed requests. See the Module 8 README for the code and how to run it.

SectionGuideWhat you will learn
1Write Request and Response Filters in REST AssuredFilters that change requests and see responses, lambda filters, filters that fail a test, OrderedFilter, and filters in a specification or globally
2Write Timing, Masking and Repair Filters in REST AssuredTiming every exchange, a log with IBANs and names masked, the built-in logging filters, and repairing a response with ResponseBuilder
3Sign Requests With HTTP Message Signatures in REST AssuredSigning requests with RFC 9421 and a Content-Digest in a filter that runs last, and proving the server rejects unsigned, tampered, wrongly signed and stale requests
4Write a Custom Authentication Scheme in REST AssuredAn API key scheme with ContextAuthenticationScheme, removing it with auth().none(), replacing it, and why a scheme beats a header
5Use Parsers and Failure Listeners in REST AssuredReading JSON sent as text/plain with a parser, why a spec’s parser doesn’t reach chained checks, and collecting evidence with a failure listener

Module 8 Build Module 8: Build & Test Results

Module 9: Data-Driven Tests and API Workflows

How to test many inputs without copying tests, generate tests at run time, test multi-step workflows, check the HTTP semantics payment APIs depend on, and wait for asynchronous work. The tests run against a payment lifecycle API, from initiation to execution. See the Module 9 README for the code and how to run it.

SectionGuideWhat you will learn
1Write Parameterized API Tests With REST AssuredA validation matrix in a @CsvSource text block, boundary values, @FieldSource and @MethodSource, a class per currency with @ParameterizedClass, and logging only failures
2Generate Dynamic API Tests With REST AssuredGenerating security tests for every endpoint at run time, grouping them with dynamicContainer, and when to choose dynamic over parameterized tests
3Test API Workflows With REST AssuredA payment lifecycle as ordered steps sharing one instance, why independent tests are better, and testing the transitions that must be refused
4Test Idempotency, ETags and Pagination in REST AssuredIdempotent replay with an Idempotency-Key, 304, 428 and 412 with ETags, and following Link headers through every page
5Test Asynchronous APIs With REST AssuredPolling a Location with Awaitility instead of Thread.sleep, respecting Retry-After, and waiting for any final state before checking which one

Module 9 Build Module 9: Build & Test Results

Module 10: Stubbing Dependencies with WireMock

How to test an API whose own dependency you don’t control: REST Assured calls your API, and WireMock plays the third-party API it calls. The tests run against a quote service that asks an FX provider for exchange rates. See the Module 10 README for the code and how to run it.

SectionGuideWhat you will learn
1Stub a Dependency With WireMock in REST Assured TestsWireMockExtension, strict request patterns, a stubbed rate and half-even rounding, unmatched requests, and input that never reaches the provider
2Simulate Provider Faults With WireMock in REST Assured TestsServer errors, delays, reset connections, broken JSON, rate limiting and unknown currencies, and what your API’s clients should see for each
3Verify Outgoing Calls With WireMock in REST Assured Testsverify(..) with exact counts, query parameters and headers, one retry for a 503, no retry for a 500, and reading recorded requests
4Use Response Templates and Scenarios in WireMock StubsOne templated stub for every currency, and scenarios in which the provider fails and recovers, to prove a retry gives up or saves a request

Module 10 Build Module 10: Build & Test Results

Module 11: Spring Boot Integration

The ways to test a Spring Boot API with REST Assured: RestAssuredMockMvc without a server, a web slice with Spring Security, and plain REST Assured against the whole application on a random port, plus keeping versions aligned under Spring Boot’s dependency management. The tests run against a Spring Boot 4.1 accounts service secured as an OAuth 2.0 resource server. See the Module 11 README for the code and how to run it.

SectionGuideWhat you will learn
1Test a Spring Controller With RestAssuredMockMvc in Standalone ModeTesting a controller with standaloneSetup(..), no server and no Spring context, and what that mode leaves out
2Test Spring Security Rules in a Web Slice With RestAssuredMockMvcTesting the security rules in a @WebMvcTest slice with Spring Security’s jwt() post-processor, 401, 403 insufficient_scope and problem details
3Test Spring Boot on a Random Port With REST Assured and Real TokensThe whole application on a random port over real HTTP, with signed test tokens that check signature, expiry, audience and scope
4Keep Versions Aligned Under Spring Boot’s Dependency ManagementWhat Spring Boot 4.1 manages, why the first imported BOM wins, and checking resolved versions with dependency:tree

Module 11 Build Module 11: Build & Test Results

Module 12: Real Infrastructure with Testcontainers

How to run REST Assured against real infrastructure in Docker, and make a large suite fast and organised: real OAuth 2.0 tokens from Keycloak, parallel execution, and tags with Maven profiles. The tests run against an API protected by a real Keycloak, and a reference data API. The Keycloak tests need Docker. See the Module 12 README for the code and how to run it.

SectionGuideWhat you will learn
1Test With Real OAuth 2.0 Tokens From Keycloak and TestcontainersKeycloak in Docker with Testcontainers, OpenID Connect discovery, real tokens with the client credentials grant, and the claims a real server puts in them
2Run REST Assured Tests in Parallel With JUnitOpt-in parallel execution with junit-platform.properties and @Execution(CONCURRENT), and the rules that make REST Assured safe in parallel
3Run the Right Subset of a REST Assured Suite With Tags and Maven ProfilesTags and a composed @SmokeTest, Maven profiles that set groups and excludedGroups, tag expressions, and a suite in a pipeline

Module 12 Build Module 12: Build & Test Results

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