Show List

Using Rest Assured with Basic Authentication

Here's an example Java program that demonstrates how to use Rest Assured to test a GET request to a REST API endpoint with Basic Authentication:


import io.restassured.RestAssured; import io.restassured.response.Response; public class ApiGetWithBasicAuthTest { public static void main(String[] args) { // Set base URI of the REST API RestAssured.baseURI = "https://api.example.com"; // Set basic authentication credentials String username = "your_username"; String password = "your_password"; // Send GET request to /endpoint with basic authentication Response response = RestAssured.given() .auth() .preemptive() .basic(username, password) .get("/endpoint"); // Get and print the response body String responseBody = response.getBody().asString(); System.out.println("Response Body:"); System.out.println(responseBody); // Get and print the status code int statusCode = response.getStatusCode(); System.out.println("\nStatus Code: " + statusCode); } }

In this example:

  • We set the base URI of the REST API using RestAssured.baseURI.
  • We set the basic authentication credentials using .auth().preemptive().basic(username, password).
  • We send a GET request to the specified endpoint with basic authentication using RestAssured.given().auth().preemptive().basic(username, password).get("/endpoint").
  • We retrieve the response body and status code from the response object and print them out.

Replace "https://api.example.com" with the base URI of your REST API, and "your_username" and "your_password" with your actual username and password for basic authentication. Additionally, replace "/endpoint" with the specific endpoint you want to test. Make sure you have Rest Assured and its dependencies added to your project's classpath.


    Leave a Comment


  • captcha text