Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Testing REST APIs with REST Assured

July 20, 2017
Heiko Rupp
Related topics:
Developer ToolsJavaMicroservices
Related products:
Developer Tools

Share:

    Note: This is an updated version of a post I wrote for my private blog years ago.

    While working on the REST API of RHQ a long time ago, I had started writing some integration tests against it. Doing this via pure HTTP calls is very tedious and brittle. So, I was looking for a testing framework to help me and found one that I used for some time. I tried to enhance it a bit to better suit my needs but didn't really get it to work.

    I started searching again and this time found REST Assured, which is almost perfect as it provides a high-level fluent Java API to write tests. REST Assured can be used with the classic test runners like JUnit or TestNG.

    Let's have a look at a very simple example:

    @Test
    public void testStatusPage()
    {
      expect()
         .statusCode(200)
         .log().ifError()
      .when()
         .get("/status/server");
    }

    As you can see, this fluent API that is very expressive, so I don't really need to explain what the above is supposed to do. The example also shows that REST Assured is using defaults for the target server IP and port.

    In the next example, I'll add some authentication.

    given()
         .auth().basic("user","name23")
      .expect()
         .statusCode(401)
      .when()
         .get("/rest/status");

    Here we add authentication "parameters" to the call, which are in our case the information for basic authentication, and expect the call to fail with a "bad auth" response to ensure that a user with bad credentials can't log in. You can see that we do not need to know how the authentication is actually translated into an HTTP-header but can concentrate on the logic.

    As it is tedious to always provide the authentication bits throughout all tests, it is possible to tell Rest Assured in the test setup to always deliver a default set of credentials, which can still be overwritten as just shown:

    @Before
    public void setUp() {
       RestAssured.authentication = basic("rhqadmin","rhqadmin");
    }

    There are a lot more options to set as default, like the base URI, port, basePath and so on.

    Now let's have a look on how we can supply other parameters and retrieve a result from the POST request.

    AlertDefinition alertDefinition = new AlertDefinition(….);
      Header acceptJson = new Header("Accept", "application/json")
    
      AlertDefinition result =
      given()
         .contentType(ContentType.JSON)
         .header(acceptJson)
         .body(alertDefinition)
         .log().everything()
         .queryParam("resourceId", 10001)
      .expect()
         .statusCode(201)
         .log().ifError()
      .when()
         .post("/alert/definitions")
      .as(AlertDefinition.class);

    We start with creating a Java object AlertDefinition that we use for the body of the POST request. We define that it should be sent as JSON by passing a ContentType and that we expect JSON back via the acceptJson that we defined earlier. For the URL, a query parameter with the name 'resourceId' and value '10001' should be appended.

    We also expect that the call returns a 201 - created and would like to know the details are, this is not the case. Last but not least, we tell Rest Assured, that it should convert the answer back into an object of a type AlertDefinition which we can then use to check constraints or further work with it.

    JSON Path

    Rest Assured offers another interesting and built-in way to check constraints with the help of XmlPath or it's JSON-counterpart JSON Path, which allows formulating queries on JSON data like XPath does for XML.

    Suppose our REST-call returns the following JSON payload:

    {
      "vendor": [
        {
          "name": "msc-loaded-modules",
          "displayName": "msc-loaded-modules",
          "description": "Number of loaded modules",
          "type": "gauge",
          "unit": "none",
          "tags": "tier=\"integration\"",
          "multi": false
        },
        {
          "name": "BufferPool_used_memory_mapped",
          "displayName": "BufferPool_used_memory_mapped",
          "description": "The memory used by the pool: mapped",
          "type": "gauge",
          "unit": "byte",
          "tags": "tier=\"integration\"",
          "multi": false
        },
        {
          "name": "BufferPool_used_memory_direct",
          "displayName": "BufferPool_used_memory_direct",
          "description": "The memory used by the pool: direct",
          "type": "gauge",
          "unit": "byte",
          "tags": "tier=\"integration\"",
          "multi": false
        }
      ]
    }

    One can then run the following queries (preceded by a '> ') and get the results below it.

    # Get the names of all the objects below vendor
    > vendor.name
    [msc-loaded-modules, BufferPool_used_memory_mapped, BufferPool_used_memory_direct]
    # Find the name of all objects below 'vendor' that have a unit of 'none'
    > vendor.findAll { vendor -> vendor.unit == 'none' }.name
    [msc-loaded-modules]
    # Find objects below vendor that have a name of 'msc-loaded-modules' 
    vendor.find { it.name = 'msc-loaded-modules' }
    {unit=none, displayName=msc-loaded-modules, name=msc-loaded-modules, description=Number of loaded modules, type=gauge, tags=tier="integration", multi=false}

    In the previous example, there is mystical it, which represents the expression before the find keyword.

    You can then use those queries in your code to do something like the following to check that the returned data is indeed the expected one.

    // Do an OPTIONS call to the remote and then translate into JsonPath
    JsonPath jsonPath =
        given()
          .header("Accept",APPLICATION_JSON)
        .options("http://localhost:8080/metrics/vendor")
          .extract().body().jsonPath();
    
    // Now find the buffer direct pool
    Map<String,String> aMap = jsonPath.getMap("find {it.name == 'BufferPool_used_memory_direct'}");
    // And make sure its display name is correct
    assert directPool.get("displayName").equals("BufferPool_used_memory_direct");

    Note, that the JSONPath expressions follow the Groovy GPath syntax. I have created a small JsonPath explorer that can be used to test queries against a given JSON input document.

    Matchers

    The other strong point of Rest Assured is the possibility to use so called Matchers from Hamcrest project as in,

    when()
       .get("http://localhost:8080/metrics/base")
    .then()
       .header("ETag",notNullValue())
       .body("scheduleId", hasItem( numericScheduleId)) 
       .body(containsString("total-started-thread-count"));

    Here the containsString(), notNullValue() and hasItem() methods are such a matchers that look for the passed expression in all of the message body retrieved from the call to the REST API. Using the matches again make the test code very expressive and ensure good readability.

    Conclusion

    Rest Assured is a very powerful framework to write tests against a REST/hypermedia API. With its fluent approach and the expressive method names, it allows to easily understand what a certain call is supposed to do and to return. Both JSONPath and Matchers further increase the power and expressiveness.

    Further reading

    • The Rest Assured web site has more examples and documentation.
    • The mentioned RHQ project has a larger number of tests that can serve as examples.
    • Here is a good walk through of the capabilities of JSONPath via Groovy GPath.

    To build your Java EE Microservice visit WildFly Swarm and download the cheat sheet.

    Last updated: February 6, 2024

    Recent Posts

    • Skopeo: The unsung hero of Linux container-tools

    • Automate certificate management in OpenShift

    • Customize RHEL CoreOS at scale: On-cluster image mode in OpenShift

    • How to set up KServe autoscaling for vLLM with KEDA

    • How I used Cursor AI to migrate a Bash test suite to Python

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue