Rest Assured is one of the most popular libraries which is highly used in API Test Automation in most companies. In this Rest Assured tutorial, I will try to explain Rest API, API Testing, API Automation, REST, and SOAP protocols.
Rest Assured Tutorial Outline
In this post, I will explain what is API and API testing, what is the difference between SOAP and REST services, and how to test REST APIs with Rest Assured Library.
What is API?
API stands for Application Programming Interface. It comprises a set of functions that can be accessed and executed by another software system. Thus, it serves as an interface between different software systems and establishes their interaction and data exchange.
What is API Testing?
In the modern development world, many web applications are designed based on a three-tier architecture model. These are 1) Presentation Tier – User Interface (UI) 2) Logic Tier – Business logic is written in this tier. It is also called Business Tier. (API) 3) Data Tier – Here information and data are stored and retrieved from a Database. (DB) Ideally, these three layers (tiers) should not know anything about the platform, technology, and structure of each other.
We can test UI with GUI testing tools and we can test logic tier (API) with API testing tools. The logic tier comprises all of the business logic and it has more complexity than the other tiers and the test executed on this tier is called API Testing. API testing tests the logic tier directly and checks expected functionality, reliability, performance, and security.
In the agile development world, requirements are changing during short release cycles frequently and GUI tests are more difficult to maintain according to those changes. Thus, API testing becomes critical to test application logic. In GUI testing we send inputs via keyboard texts, button clicks, drop-down boxes, etc., on the other hand in API testing we send requests (method calls) to the API and get output (responses). These APIs are generally REST APIs or SOAP web services with JSON or XML message payloads being sent over HTTP, HTTPS, JMS, and MQ.
[Ref: wiki] I don’t want to go into the theory so much in this post. If you want to learn more theory of API testing, you can visit the below websites.
https://www.soapui.org/testing-dojo/world-of-api-testing/what-makes-api-testing-special-.html
https://en.wikipedia.org/wiki/API_testing
REST vs SOAP
REST (Representational State Transfer)
REST is an architectural style that uses simple HTTP calls for inter-machine communication. REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier, and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource. [1][2][6]
SOAP (Simple Object Access Protocol)
SOAP relies heavily on XML, and together with schemas, defines a very strongly typed messaging framework. Every operation the service provides is explicitly defined, along with the XML structure of the request and response for that operation. Each input parameter is similarly defined and bound to a type: for example, an integer, a string, or some other complex object. All of this is codified in the WSDL – Web Service Description (or Definition, in later versions) Language.
The WSDL is often explained as a contract between the provider and the consumer of the service. SOAP uses different transport protocols, such as HTTP and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifications to the SOAP protocol. [3][4][6]
References:
http://searchsoa.techtarget.com/definition/REST [1]
http://blog.pluralsight.com/representational-state-transfer-tips [2]
https://www.soapui.org/testing-dojo/world-of-api-testing/soap-vs–rest-challenges.html [3]
http://blog.smartbear.com/apis/understanding-soap-and-rest-basics/ [4]
http://spf13.com/post/soap-vs-rest [5]
http://searchsoa.techtarget.com/tip/REST-vs-SOAP-How-to-choose-the-best-Web-service [6]
REST API Testing with Rest Assured
What is Rest Assured?
In order to test REST APIs, I found the REST Assured library so useful. It is developed by JayWay Company and it is a really powerful catalyzer for automated testing of REST services. REST-assured provides a lot of nice features, such as DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads, and with those features, we will handle automated API testing much easier. Rest Assured has a gherkin type syntax which is shown below code. If you are a fan of BDD (Behavior Driven Development), I believe that you will love this kind of syntax.
@Test public void exampleRestTest() { given() .contentType(ContentType.JSON) .pathParam("id", "AskJsd8Sd") .when() .get("/examplepath/{id}") .then() .statusCode(200) .body("firstName", equalTo("Onur")) .body("Surname", equalTo("Baskirt")); }
Also, you can get JSON response as a string and send it to the JsonPath class and use its methods to write more structured tests. I generally prefer JsonPath for more structured tests.
@Test public void exampleJsonPathTest() { Response res = given().get("/service/example"); assertEquals(200, res.getStatusCode()); String json = res.asString(); JsonPath jp = new JsonPath(json); assertEquals("onur@swtestacademy", jp.get("email")); assertEquals("Onur", jp.get("firstName")); assertEquals("Baskirt", jp.get("lastName")); }
How to Make a POST Request with RestAssured?
The following code uses requestSpecBuilder to make a post request. Parameter descriptions are listed below.
- restAPIURL – URL of the Rest API
- APIBody – Body of the Rest API. Example: {“key1″:”value1″,”key2″:”value2”}
- setContentType() – Pass the “application/json”, “application/xml” or “text/html” etc. headers to setContenType() method.
- Authentication credentials – Pass the username and password to the basic() method or if there is no authentication leave them blank basic(“”,””)
@Test public void httpPostMethod() throws JSONException, InterruptedException { //Rest API's URL String restAPIUrl = "http://{URL of API}"; //API Body String apiBody = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}"; // Building request by using requestSpecBuilder RequestSpecBuilder builder = new RequestSpecBuilder(); //Set API's Body builder.setBody(apiBody); //Setting content type as application/json builder.setContentType("application/json; charset=UTF-8"); RequestSpecification requestSpec = builder.build(); //Making post request with authentication or leave blank if you don't have credentials like: basic("","") Response response = given() .auth() .preemptive() .basic({ username }, { password }) .spec(requestSpec) .when() .post(restAPIUrl); JSONObject JSONResponseBody = new JSONObject(response.body().asString()); //Get the desired value of a parameter String result = JSONResponseBody.getString({ key }); //Check the Result Assert.assertEquals(result, "{expectedValue}"); }
Gherkin Style Rest Assured POST Request
@Test public void postExamplebyGherkin(){ RestAssured.baseURI = "Your API URL"; Response res = given() .contentType("application/json") .body("{\"name\":\"Onur Baskirt\"}") .when() .post(""); String body = res.getBody().asString(); System.out.println(body); }
For more theory, please visit references. I want to go with example questions and their solutions.
References:
https://rest-assured.io/[1] (Rest Assured GitHub page)
http://www.javahotchocolate.com/notes/rest-assured.html [4]
http://artoftesting.com/automationTesting/restAPIAutomationPostRequest.html [5]
https://automationqahub.com/how-to-test-graphql-using-rest-assured/ [6] For GraphQL Testing with RestAssured.
API Testing Automation Examples
Example-1:
Test Description: Get the clients from https://generator.swagger.io/. We will do a GET request to get and print all clients.
Base URL: https://generator.swagger.io/
Resource Path: /gen/clients
We will verify the status and print the clients which we get from the API.
Example-2:
Test Description: Get android clients. Then, check the status and print modelPackage.opt, modelPackage.description, and modelPackage.type values.
API Testing Automation Solutions
Strategy: First, it is very reasonable to use a framework/library which provides us to test an API easily in a short period of time and we chose the Rest-assured library. It is better to write the code with the below rules.
Project Structure:
We have utility functions and test classes.
BasicAPiTest contains our test implementations.
I used TestNG as a test runner framework and all dependencies are in pom.xml file.
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>api-automation-basic</groupId> <artifactId>api-automation-basic</artifactId> <version>1.0-SNAPSHOT</version> <properties> <rest-assured-version>4.4.0</rest-assured-version> </properties> <dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>${rest-assured-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>${rest-assured-version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-path</artifactId> <version>${rest-assured-version}</version> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-schema-validator</artifactId> <version>${rest-assured-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> </plugins> </build> </project>
TestNG.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name="API Testing Suite" verbose="1"> <test name="Nopackage"> <classes> <class name="BasicApiTest"/> </classes> </test> </suite>
I tried to explain the other codes line by line. Now I want to go on with the project’s JAVA files.
RestAssuredUtil.java
RestAssuredUtil.java It is a utility class for Rest Assured Library. It contains many methods that help us to write our codes more effectively.
package utils; import static io.restassured.RestAssured.given; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; public class RestAssuredUtil { //Sets Base URI public static void setBaseURI() { RestAssured.baseURI = "http://generator.swagger.io/"; } //Sets base path public static void setBasePath(String basePathTerm) { RestAssured.basePath = basePathTerm; } //Reset Base URI (after test) public static void resetBaseURI() { RestAssured.baseURI = null; } //Reset base path public static void resetBasePath() { RestAssured.basePath = null; } //Sets ContentType public static void setContentType(ContentType Type) { given().contentType(Type); } //Returns response by given path public static Response getResponse(String path) { return given().get(path); } //Returns response public static Response getResponse() { return given().get(); } //Returns JsonPath object public static JsonPath getJsonPath(Response res) { String json = res.asString(); return new JsonPath(json); } }
TestUtil.java
We will get the clients and check the status code in this class.
package util; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import java.util.ArrayList; import org.testng.Assert; public class TestUtil { //Verify the http response status returned. Check Status Code is 200? public void checkStatusIs200(Response res) { Assert.assertEquals(res.getStatusCode(), 200, "Status Check Failed!"); } //Get Clients public <T> ArrayList<T> getClients(JsonPath jp) { return jp.get(); } }
BasicApiTest.java
We have some basic API tests in our test class.
import org.testng.annotations.Test; public class BasicApiTest extends BaseTest { @Test public void T01_StatusCodeAndGetClientsTest() { res = utils.RestAssuredUtil.getResponse("/gen/clients"); testUtil.checkStatusIs200(res); jp = utils.RestAssuredUtil.getJsonPath(res); System.out.println(testUtil.getClients(jp)); } @Test public void T02_GetAndroidModelPackageOptions() { res = utils.RestAssuredUtil.getResponse("/gen/clients/android"); testUtil.checkStatusIs200(res); jp = utils.RestAssuredUtil.getJsonPath(res); System.out.println("Opt: " + jp.get("modelPackage.opt")); System.out.println("Description: " + jp.get("modelPackage.description")); System.out.println("Type: " + jp.get("modelPackage.type")); } }
Let’s run our tests by right-clicking the TestNG.xml file and then click the to run option.
GitHub Project
https://github.com/swtestacademy/api-automation-rest-assured-basic
Thanks for reading.
Onur Baskirt

Onur Baskirt is a Software Engineering Leader with international experience in world-class companies. Now, he is a Software Engineering Lead at Emirates Airlines in Dubai.
Hi
Can we use cucumber features to run API test.
If so what does the framework involve.
Please suggest any..
Of course you can. I did not do this before but when I googled it, I found below articles. Most of them are using Ruby to do this. You can find a lot of results when you search “api test with cucumber” on google.
http://gregbee.ch/blog/effective-api-testing-with-cucumber
http://www.hidroh.com/2015/03/08/test-external-api-like-boss-cucumber/
thank you..
Hi Onur,
Good Blog on API testing with Rest-Assured..!!!
Do you have any working example that you can illustrate on POST request passing the data dynamically ( read JSON file and pass in test script).
Hi Varun,
I do not have any working example. Now, I am in a vacation. I will also check after vacation.
Hi Onur,
Very helpful article. Thank you for giving such an explanation with relevant examples. It really helped in my project.
Thank you Swati. :)
Very helpful.
Thanks Ram. ;)
Can you please give an example how to post a complex Json post body (POST Method) with data provider. the Post body should be constructed with the values from dataprovider.
Hi Dilip,
I did a search and found below articles. I hope this helps.
http://www.ontestautomation.com/creating-data-driven-api-tests-with-rest-assured-and-testng/
http://james-willett.com/2015/06/going-further-with-rest-assured-part-2-parameterised-testing-with-junitparams/
https://www.linkedin.com/pulse/rest-api-automation-using-http-client-amit-tayade/
Nice post Amit.
Hi Baskirt,
Thanks for detailed explanation. We are trying to implement the same. I am getting exception at ‘AfterTest’ method.
Am i missing any configuration?
public void afterTest (){
//Reset Values
RestUtil.resetBaseURI();
RestUtil.resetBasePath();
}
java.lang.IllegalArgumentException: baseURI cannot be null
Please check here and debug your program carefully.
https://examples.javacodegeeks.com/java-basics/exceptions/java-lang-illegalargumentexception-how-to-solve-illegal-argument-exception/
Hi Baskirt,
I have my test cases written in SOAP UI PRO tool, is there any way that i can migrate those TCs to Rest Assured?
Hi Param,
If web services are communicating with JSON or XML you can transfer it to REST-Assured. I suggest you to check this article. http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework/
thank you. very useful article.
Hi Onur,
I am really happy that you have posted this article . Thank you so much for this article and it really helped me.
Do you have any working example that you can illustrate on POST request passing the data dynamically ( read JSON file and pass in test script).
Thank you. I do not have that example but I found this article for you. https://semaphoreci.com/community/tutorials/testing-rest-endpoints-using-rest-assured Please check “Sending Test JSON Data with POST Calls” section.
Hi Onur, I’m thinking of using Rest Assured for my API testing, then I saw RunScope online where you can monitor tests and run tests + implementation of tests are easy. Do you know if Rest Assured is still to prefer or should I go for RunScope?
Hi Neda,
If you want to use open-source solution you can use RestAssured. It is also not hard to use it and it has a significant community. When u get in trouble, you can find many blog articles or StackOverflow questions/answers. But If you want to go faster and much easier tool, you can go with Runscope. If I were you, I would try RestAssured for 2-3 weeks. If I could not reach my goals, then I switch to RunScope. But If you have very limited time and if you need to give a decision quickly, you can go on with RunScope.
Hi.. It is a nice post..
I recently tried a new framework ‘Karate’ for REST API automation.
Below is the link
https://github.com/intuit/karate
They are claiming that it is a really good tool which is lot better than Rest-Assured. I am bit confused in choosing in between these two framework for our API automation.Could you please suggest is Karate really good.Or are there any drawbacks?
I haven’t tried Karate but RestAssured is a good library.
I am using Version 0.1.9 of Rest Assured for .Net. I wanted to use https for sending the request instead of http.
Please could you advice if there is some way to use https as UseHttps() is not working.
I did not have any experience on .NET. It is better to google it that problem ;)
@Onur Baskirt, Thanks alot.
I really learned too much about restful api testing through your written, could you please help me out for connecting database to get expectedresult in below script:
//@Test
public void test_07(){
Response resp = given().
param(“userid”,”40″ ).
param(“user_id”, “72”).
param(“token”, “any toekn”).
when().
get(“http://iloverestapitesting”);
String actualUserReport = resp.
then().
contentType(ContentType.JSON).
extract().
path(“user_detail.email”);
String expectedUserReport = null;——>> help me out here for database connection
if(actualUserReport.equals(expectedUserReport)){
System.out.println(“User Report API is working fine and test case pass”);
}
else{
System.out.println(“User Report is not found and API is not working fine and test case failed”);
}
Please check this article for JDBC connection with JAVA ;) https:/database-operations-javafx/
It is better to write DBOperations Utility class to handle DB related operations.
Hi Onur,
It has been a very helpful article. thank you
I am having a problem. when validating a schema, if a value returns null, rest assured throw assertion error. how can i fixed it ?
Thanks, Serhat. Have you tried try/catch block? I also found this link. They also offered to catch the exception with AssertionError. https://stackoverflow.com/questions/19390295/rest-assured-exception-when-test-fails
Onur thanks for answering. I had been different problem. But i was find correct reason. Json Schema i used was incorrect.
incorrect schema:
“installment”: {
“id”: “/properties/installment”,
“type”: “integer”
},
correct schema need to use:
“installment”: {
“id”: “/properties/installment”,
“type”: [“integer”,”null”]
},
It’s great to hear that you solved the problem. Good luck on your project. ;)
HI Onur,
1. Could you please let me can i Connect to Jenkins for CI? I need to run my APi every 10 mins and genrate reports and get email notification if response code is not 200?
2. Does RA supports Database testing?
3. My response content type is “text/xml” i am finidng most of the examples in JSON only. could u please give me some examples on XML, and XML methods??
4. could u please give Data Driven example on RA from reading or validating from excel sheet? or extracting all url from excel sheet one after one.
Thanks,
1. Yes, you can connect with Jenkins. You should use like “mvn test –PallApiTests” command to integrate with Jenkins.
Open Jenkins
Manage Jenkins
Global Tool Configuration
Set JDK and Maven settings. Write their paths.
Open your build job.
Build -> Invoke top-level Maven Targets (Select This)
Goals = mvn test –PallApiTests (write your test suite instead of -PallApiTests
Report generation depends on you reporting libraries. Please, Check surefire, testNG, JUnit reporting on google. For testNG, use select “Publish TestNG Results” for a post-build action and set your results.xml as a TestNG XML report pattern. Schedule Jenkins as shown here. https://stackoverflow.com/questions/12472645/how-to-schedule-jobs-in-jenkins
2. For DB tests, I suggest you write a DBUtil class and use JDBC. (Check my JAVAFX Database article. You can find some tricks in that article.)
3. For XML, check here, please. https://static.javadoc.io/com.jayway.restassured/rest-assured/1.4/com/jayway/restassured/path/xml/XmlPath.html
4. Please, check Apache POI library examples on google. For example, https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/
Hi Onur,
Thank you for posting this clean and basic project example. I have a question though, in Example-1.class and Example-2.class you are running the same SetUp() method. Is there any smart way to make both test suites to use same SetUp() function?
Thanks in advance.
Hi Gökçe, of course, there is a smart way to combine setup methods. :) One of the most common ways is to write a BaseTest class and then extend it in test classes like Page Object Model. There are some problems in my code.
1- Test classes should have only test methods.
2- It is better to write common setup and teardown methods in BaseTest class.
Hi Onur,
This is a great article on API testing. Also went through your couple of articles and they are very handy.
You are welcome! I am happy to hear your comment.
Hi,
I am learning API.
Tried to execute above examples, but not executing.
Could you plz help me.
Many Thanks,
Swapnali
Yes, That API is not working. That’s why you are getting a problem. You can learn the tactics from this article and create your own solution.
Go to this example: https://github.com/swtestacademy/api-automation-rest-assured-basic
It is a basic Rest-Assured Test with TestNG.
– Become a member of Swagger.io.
– A sample URL link is given to Swagger and details of the POST & GET methods are displayed.
– The detail of the returned JSON Data is structural.
– A sample GET method is tested on the browser according to the Swagger output. The results are checked.
To avoid repetition of code whenever possible, I wrote the methods that the test methods can use frequently in the TestUtils class and the methods that the API tests use in the APIUtils class.
In my tests, I just tried to do the necessary operations. I wrote a BaseTest class to use for all tests. This includes operations to be performed before and after the tests and global variables.
Thanks Onur.
So whatever example you showed, that is the way to write tests for REST API?
Thanks
Welcome. Yes all of them are for REST APIs. Also, you can use KARATE. There is an article about karate here: https:/karate-web-service-testing/
Hi,
I followed above step, got following
Swagger Petstore
1.1
[ Base URL: virtserver.swaggerhub.com/hub4/Test/1.0.0 ]
This is a sample Petstore server. You can find
out more about Swagger at
http://swagger.io or on
irc.freenode.net, #swagger.
Could you plz help me on this? Which link i can use as URL.
I got HTTP ERROR 404
could you please tell whats wrong?
Thanks
1) Go to http://petstore.swagger.io/#/pet/addPet this address. (POST /pet Add a new pet to the store)
2) Click try it out button.
3) Execute below code:
{
“id”: 2,
“category”: {
“id”: 2,
“name”: “string”
},
“name”: “test-swtestacademy-dog”,
“photoUrls”: [
“string”
],
“tags”: [
{
“id”: 0,
“name”: “swtest-academy-test-tag”
}
],
“status”: “available”
}
4) Go to “/pet/{petId}Find pet by ID”
5) Click try it out.
6) type 2 as id.
7) click execute.
Then you will see the results that you added at first step.
The URL will be: http://petstore.swagger.io/v2/pet/2
Thanks Onur.
geting response in XML. How to get response in JSON in browser?
Thanks
You need to select “Response content type” = application/json in dropdown.
using “http://petstore.swagger.io/v2/pet/2” in browser, it showing response in XML.
How to get response in JSON or it will be always XML in browser
2
string
55
prashant
string
available
2
string
Hi,
I have imported your project, at POM i am getting error for xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd
can you please tell me what i have to do remove this error?
I don’t understand your exact problem. Maybe it is a connection problem?
Rest Assured or Soap Ui which is better??
If your coding skills good and if you know JAVA, Rest-Assured is good. If you want to use a tool and use groovy, then SOAP-UI.
Thanks ,Can we do both web service and API testing using rest assured ,As far I know using Soap UI we can test both.
Which has more features Soap UI or rest assured and which is easy to use
Hi I think your approach will be bit difficult to maintain if my response json will be huge we have to write json path to extract the JSON.
Instead why don’t we go for model class mapping way(pojo class) map your response with model class from that we can extract the data.
You can use your POJO approach too. I applied a similar approach in my JavaFX article. https:/database-operations-javafx/
Hi,
If I have to use Groovy scripting along with selenium for REST APIs, how do I approach?
Hello Manjula, in Baeldung there is an article for this: baeldung.com/rest-assured-groovy I hope it helps.
I got HTTP ERROR 404
could you please tell what’s wrong?
Thanks
Hello, The example API is old. You should get the fundamental from the article and try to implement it for your own API. Best Regards.
Hi Onur, Thank you for your tutorial, I am starting to learn API testing but there are many tools and I don’t know how to start manual, then automated?!
I saw many tutorials but, you know, none of them start similar to you from zero points, could you please let me know if you know any good resource? my colleague recommended starting with the postman, what is your idea?
Yes you can use POSTMAN to check the endpoints and their functionality. After that check the responses in JSON viewer websites online. After that, you can start to automate them even using POSTMAN or writing a JAVA project with Rest-Assured or Rest Template or OKhttp or similar libraries. I suggest Rest-Assured because it is very QA friendly. I hope this helps.
good article
Hi Onur,
I am getting java.net.ConnectException: Connection timed out: connect error.
That API is not working anymore I guess. You can get the idea of the solution and apply to your API.
Thanks for the reply Onur.
API is working fine. I hit the API in Postman, getting 200 OK status.
http://ergast.com/api/f1/2017/circuits.json
PFB Postman Headers details –
KEY VALUE
Date Mon, 04 Nov 2019 08:16:42 GMT
Server Apache/2.2.15 (CentOS)
X-Powered-By PHP/5.3.3
Access-Control-Allow-Origin *
Content-Type application/json; charset=utf-8
Transfer-Encoding chunked
Connection Keep-Alive
Content-Encoding gzip
Could you please help me on this.
Dear Varsha, it may have several reasons. Please debug the problem. I can not say a certain solution without debugging the problem. https://stackoverflow.com/questions/86824/why-would-a-java-net-connectexception-connection-timed-out-exception-occur-wh
Hi,I am consuming APIs from one service ,so is it possible to use rest assured framework for testing in service ?
Yes you can use rest assured. If it is a rest service you can use post, get, put, patch, delete, etc. method’s of rest assured to test the service.
hello
HEllo Prasad.
Hello,
I want to automate API testing and i’m really confused between rest assured and postman as postman also provide newman to automate CI/CD using scripting.
Do you think that Rest assured is better than postman?
Thank you
Abdelhak
Hello, we are using POSTMAN for exploratory testing of APIs but also you can use it for automated way. On the other hand, we are using rest assured for automation because it gives us full flexibility and maintainability. If you have a very modular and maintainable framework, you can implement further changes easily with minimal effort.
nice work
Thank you.
Great Article, very well explained. Could you also suggest How to write API request method in ApiMethods.java?
Very well explained as usual. Thanks for the knowledge sharing
Welcome. :)
Hi Onur, hope you are doing good!
Can you please suggest me any article related to RestAssured in C# (BDD Specflow)
Mainly when the request body is of “x-www-form-urlencoded” format.
Thank you in advance :)
I suggest you to check execute automation channel on youtube. Kartik K.K. He has many tutorials on C# based automation frameworks.
Thnx Onur for the article. it really helped me in understanding.
In case any one here faces any problem like “testng-error-cannot-find-class-in-classpath” use package name before class name in testng.xml like -> ” TestClass.BasicApiTest”
Welcome Sai. I did not face that problem. Maybe you can find some hints from here: https://stackoverflow.com/questions/7600898/testng-error-cannot-find-class-in-classpath
Thanks .. Nice Article and its very useful for beginners :)
Welcome. I will write an advanced version soon. ;)
Nice Article. Need your help in one weird issue I am facing with RestAssured to validate one GET call on BookStore API. It’s working fine in Curl..
Working CURL Command as below:
curl -X GET “https://bookstore.xxxx.com/Account/v1/User/f00600d9-dc34-46e7-84f1-9404410b7f74” -H “accept: application/json” -H “authorization: Basic Qm9va1Rlc3RlcjEyOlRlc3RlciMxMg==”
AND It Returns JSON Response as expected.
Now, I am calling same API using RestAssured with code as below:
RestAssured.given().header(“accept”, “application/json”)
.header(“authorization”, “Basic Qm9va1Rlc3RlcjpUZXN0ZXIjMTI=”)
.when()
.get(“https://bookstore.xxxx.com/Account/v1/User/5641c9d9-1e3f-45be-a752-e1cc9d31e151”)
But it’s not giving any JSON response but HTML default page.
Please suggest.
Hi, when you get the RestAssured response, you need to deserialize it with the response DTO class as shown below.
First, you can convert response JSON to a DTO class from here: https://www.jsonschema2pojo.org/
For, get and set methods, you can use Lombok Library’s @Getter and @Setter annotation to make the class leaner. Also, I suggest to use this annotation as well: @JsonIgnoreProperties(ignoreUnknown = true) for any kind of complication it will help.
Assume that we named this class as BooksResponse.
Then, you need to deserialize the Rest Assured response with this Response class as shown below.
BooksResponse bookResponse;
bookResponse = response.getBody().as(BooksResponse.class);
and then when you converted the response as you can get and use any kind of values in it.
If you want even JSON string, you can convert like below.
Supplier OBJECT_MAPPER = () -> {
final ObjectMapper mapper = new ObjectMapperConfigurer(new ObjectMapper()).getObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper;
};
/**
* This method gives you json string from pojo.
*
* @param jsonObj pass jsonObject
*/
static String getJsonStringFromPojo(final Object jsonObj) {
try {
return OBJECT_MAPPER
.get()
.writeValueAsString(jsonObj);
} catch (final IOException e) {
throw new IllegalStateException(e);
}
}
I hope these hints will help and I will write a very comprehensive and advanced API automation framework article in the future. Keep checking swtestacademy blog. :)
Great share! Thanks for the information. Keep going!