Forum Discussion

mehdi_sh's avatar
mehdi_sh
New Contributor
6 years ago

How to send a API request with authorization Token via a Groovy script?

Hello,

I want to call a REST APi with a authorization token via my groovy script. How may i do this?

Thanks

  • Hi, 

     

    You can use Java - Unirest to send the API request with authorization token:-

    //Considering you have already fetched the Authorization Token
    import com.mashape.unirest.http.Unirest;
    import com.mashape.unirest.http.HttpResponse;

    String accessToken = "Your Authorization Token" String token_appender = "?access_token=" + accessToken; try { HttpResponse<String> response = Unirest.get("API URL" + token_appender) .header("cache-control", "no-cache") .asString(); String responseBody = response.getBody().toString(); System.out.println("********** Response Generated **********"); System.out.println(responseBody); }catch(Exception e){ e.printStackTrace(); return; }

    This is the easiest way to do it.

     

    If it really helped you out. Please accept as solution and don't forget to give kudos. 

  • avidCoder's avatar
    avidCoder
    Super Contributor

    Hi, 

     

    You can use Java - Unirest to send the API request with authorization token:-

    //Considering you have already fetched the Authorization Token
    import com.mashape.unirest.http.Unirest;
    import com.mashape.unirest.http.HttpResponse;

    String accessToken = "Your Authorization Token" String token_appender = "?access_token=" + accessToken; try { HttpResponse<String> response = Unirest.get("API URL" + token_appender) .header("cache-control", "no-cache") .asString(); String responseBody = response.getBody().toString(); System.out.println("********** Response Generated **********"); System.out.println(responseBody); }catch(Exception e){ e.printStackTrace(); return; }

    This is the easiest way to do it.

     

    If it really helped you out. Please accept as solution and don't forget to give kudos. 

    • TanyaYatskovska's avatar
      TanyaYatskovska
      SmartBear Alumni (Retired)

      Hi mehdi_sh,

       

      Did any of the suggestions given here help you? If so, please click the Accept as a Solution button next to the post that helped you.

  • nmrao's avatar
    nmrao
    Champion Level 3
    Just curious why groovy step while REST request step is readily available for the same?
    • mehdi_sh's avatar
      mehdi_sh
      New Contributor

      Hi Rao,

      This is because of test automation; we need to verify some condition and in case trigger calling an API with sending some params such as Authentication Token, etc

      • nmrao's avatar
        nmrao
        Champion Level 3
        Of course, most of the people does the automation only.
        And everything you mentioned be done using REST Request step.
        In case you need any assertion, even that is possible to apply to the step.