Rest Assured: extract value from Response List

Viewed 27033

I have a List returned as response. I need to get one item from list using product.name and tariffPlan.name.

    [
  {
    "id": 123,
    "product": {
      "id": 1,
      "code": "credit",
      "name": "Credit"
    },
    "tariffPlan": {
      "id": 1,
      "code": "gold",
      "name": "Gold"
    }
  },
  {
    "id": 234,
    "product": {
      "id": 2,
      "code": "debit",
      "name": "Debit"
    },
    "tariffPlan": {
      "id": 1,
      "code": "gold",
      "name": "Gold"
    }
  }
]

I use Java8. Here is my method. I got List of Card.class elements. And then I need to get single Item from list with specified "product.name" and "tariffPlan.name".

public List<Card> getCardId(String productName, String tariffPlanName) {
    return given()
        .param("product.name", productName)
        .param("tariffPlan.name", tariffPlanName)
        .when().get("/").then()
        .extract().jsonPath().getList("", Card.class);
  }

Is it possible to do it with restAssured? Maybe use .param method like in my example? But in my example .param method is ignored. Thank you for your ideas.

UPD. My decision is:

 public Card getCard(String productName, String tariffPlanName) {
    List<Card> cardList = given()
        .when().get("/").then()
        .extract().jsonPath().getList("", Card.class);

    return cardList.stream()
        .filter(card -> card.product.name.equals(productName))
        .filter(card -> card.tariffPlan.name.equals(tariffPlanName))
        .findFirst()
        .get();
  }
4 Answers

Suppose you want to fetch the value of the id, when product name is "Credit" and tariffPlan is "Gold".

Use

from(get(url).asString()).getList("findAll { it.product.name == 'Credit' && it.tariffPlan.name == 'Gold'}.id");

Where url - http/https request and get(url).asString() will return a JSON response as string.

Here a kotlin example:

    @Test
    fun `creat endpoint with invalid payload should return 400 error`() {
        val responseError: List<ErrorClass> = Given {
            spec(requestSpecification)
            body(invalidPayload)
        } When {
            post("/endpoint")
        } Then {
            statusCode(HttpStatus.SC_BAD_REQUEST)
        } Extract {
            body().`as`(object : TypeRef<List<ErrorClass>>() {})
        }

        responseError shouldHaveSize 1
        responseError[0].field shouldBe "xxxx"
        responseError[0].message shouldBe "xxx"
    }
Related