4

How will I return a JSON response as a String with my code?

Purpose : I want to call getAccessToken() after it has obtained the accessToken from a json response body and need to return it as a String to be used in other methods.

The response example I'm trying to obtain:

"accessToken" : "The ID I need from here"

Code :

private String apiAccessToken;

public JsonPath getAccessToken() {
    JsonPath jsonPath = given().header("X-API-KEY", Config.API_KEY).header("session", this.sessionID)
            .header("username", this.userNameId).queryParam("code", verifiedCode).log().all()
            .get(baseUri + basePath + "/vm1/verifyCode").then().log().all().extract().jsonPath();

    this.apiAccessToken = jsonPath.get("accessToken");
    return new JsonPath(apiAccessToken);
}

[Added - Showing how I'm using solutions from comments below]

Example of how I call this method

public static String getToken(String key) {
    String res = given()
            .header("X-API-KEY", Config.API_KEY)
            .header("session", this.SessionId)
            .header("username", this.UserName)
            .queryParam("code", verifiedCode)
            .log().all()
            .get(baseUri + basePath + "/vm1 /verifyCode")
            .then()
            .log().all()
            .extract().asString();

    JsonPath js = new JsonPath(res);
    return js.get(key).toString();
}

public static String getJsonPath(Response response, String key) {
    String complete = response.asString();
    JsonPath js = new JsonPath(complete);
    return js.get(key).toString();
}

@Test
    public void testAuthValidator() throws InterruptedException, IOException, GeneralSecurityException {
        String sentCode = GmailUtility.getVerificationCode(); // Uses GMAIL API service to to read and get code from email and sends to getAccessToken
        System.out.println(sentCode);
        String Token = getToken("accessToken"); // Validates verification code. Spits out response for accessToken
        System.out.println(validator);
        driver = initializeDriver(); // Invokes Chrome
        driver.get(env.API_Website); // Goes to api website
        AuthApi auth = new AuthApi(driver);
        auth.getAuthorizeButton().click(); // Clicks a text field on webpage
        auth.getValueField().sendKeys("Token " + Token); // Need to call extracted response for the accessToken from getAccessToken.
foragerEngineer
  • 149
  • 1
  • 2
  • 13
  • 1
    Please refer this; [Extracting values from the Response after validation](https://github.com/rest-assured/rest-assured/wiki/Usage#extracting-values-from-the-response-after-validation) – kaweesha Jul 06 '20 at 03:06
  • 1
    @kaweesha - Thank you for the resource. Rest Assured seems to have alot of syntactic sugar and just so much to learn. Much appreciated as always. Bookmarked this link. – foragerEngineer Jul 06 '20 at 05:22

1 Answers1

6

Just write a simple reusable method to extract values using JSONPath and call the method in your code, here's a sample

Reusable Method :

public static String getJsonPath(Response response, String key) {
    String complete = response.asString();
    JsonPath js = new JsonPath(complete);
    return js.get(key).toString();
}

Test :

public static void main(String[] args) {

    Response res = given().header("X-API-KEY", Config.API_KEY).header("session", this.sessionID)
            .header("username", this.userNameId).queryParam("code", verifiedCode).log().all()
            .get(baseUri + basePath + "/vm1/verifyCode").then().log().all().extract().response();
    String value = getJsonPath(res, "accessToken");
    
    System.out.println(value);
}

Update :

public static String getToken(String key) {
    String res = given().header("X-API-KEY", Config.API_KEY).header("session", this.SessionId)
            .header("username", this.UserName).queryParam("code", verifiedCode).log().all()
            .get(baseUri + basePath + "/vm1 /verifyCode").then().log().all().extract().asString();
    JsonPath js = new JsonPath(res);
    return js.get(key).toString();
}

@Test
public void testAuthValidator() throws InterruptedException, IOException, GeneralSecurityException {
    String sentCode = GmailUtility.getVerificationCode();
    System.out.println(sentCode);
    String Token = getToken("accessToken");
    System.out.println(Token);
    driver = initializeDriver();
    driver.get(env.API_Website);
    AuthApi auth = new AuthApi(driver);
    auth.getAuthorizeButton().click();
    auth.getValueField().sendKeys("Token " + Token);
}

You can get any value using this

Wilfred Clement
  • 2,674
  • 2
  • 14
  • 29
  • Thank you for your response. I added your solution to a scenario I'm working on(left comments within code) to show the code flow. I'm not exactly sure how to apply what you provided to `auth.getValueField().sendKeys("Token " + **NEED ACCESS TOKEN AS STRING**);`. Can you please provide additional guidance? – foragerEngineer Jul 06 '20 at 05:20
  • 1
    Check the updated section, Also delete the getAccessToken() from your code and use the code I have given – Wilfred Clement Jul 06 '20 at 06:52
  • Ah I see. To my understanding, the `getToken` parameter is set to `String`. `extract().asString()` is used and we then return the extracted response as a String. Cool. One thing I'm noticing. The re-usable method you provided is not being called for some reason, I have updated my example code for observation, please let me know if anything looks off. – foragerEngineer Jul 06 '20 at 14:58
  • Would you be able to dial into my webex ? – Wilfred Clement Jul 06 '20 at 15:00
  • Sure, let me see how to do that. – foragerEngineer Jul 06 '20 at 15:03
  • The solution you have provided is working as expected. Thank you for your guidance on this. – foragerEngineer Jul 07 '20 at 14:19