Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Testing REST APIs with REST Assured

July 20, 2017
Heiko Rupp
Related topics:
Developer toolsJavaMicroservices
Related products:
Developer Toolset

    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

    • Protect data offloaded to GPU-accelerated environments with OpenShift sandboxed containers

    • Case study: Measuring energy efficiency on the x64 platform

    • How to prevent AI inference stack silent failures

    • Preventing GPU waste: A guide to JIT checkpointing with Kubeflow Trainer on OpenShift AI

    • How to manage TLS certificates used by OpenShift GitOps operator

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.