Search code examples
javajsoncucumberauthorizationrest-assured

How to extract accesss token value from one API response body(in one class) into another API header(in another class) in rest assured code


Have one token generation API in one class which gives the below response.

{
    "access_token": "eyJraWQiOiJNR2FOQUtYXC9pa0grNE1wTE9aS05wMGtqbXNOd0lzXC9WXC9EYm1LZ0pZdTZNPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYjBtcjc4cHNjMHIyM25nYnJqMml1MnNkNCIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoic2dwZi5wcm9kdWN0XC",
 "expires_in": 3600,
    "token_type": "Bearer"
}

Then have another Get API in another class in which I want to extract this access_token value in the header in rest assured code. So how can I take that access token value in another class?

public class Get_Service_List {
    
    private Response response;
    String BaseUrl = "https://dev.api.sgf.eus.nt/pro";
    
    
    
    
    
    @Given("Get Service list API")
    public void get_Service_list_API() {
     
        RestAssured.baseURI = BaseUrl;
        
    }

    @When("call the API with valid token and details")
    public void call_the_API_with_valid_token_and_details() {

        response = RestAssured.given()
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer "+TokenGeneration.accessToken)
                .when()
                .get("/api/protsvc/ser");
    
    }

    @Then("validate the resonse body with list of services")
    public void validate_the_resonse_body_with_list_of_services() {
       
        String response_body = response.getBody().asString();
        System.out.println("response is: " +response_body);
    }

    @Then("validate for 200 status code")
    public void validate_for_status_code() {
      
        int status_code = response.getStatusCode();
        System.out.println("status is: " +status_code);
    
    
    }
}

Solution

  • I don't know much about how cucumber share state. Below is the way to extract access_token from response.

    String accessToken = response.jsonPath().getString("access_token");