Rest-Assured Rest
Rest-Assured Rest
If you’re using Java, Rest-Assured would be my first choice for API automation.
Rest-assured is a fluent Java library you can use to test HTTP-based REST services. It’s designed with testing in mind, and it inte
I’ll admit upfront that this is the main tool I use for API testing. It provides a BDD-like DSL that makes creating API testing in Jav
from scratch. Bonus: if you’re like me and use the Serenity automation framework, Rest-assured integrates seamlessly with it,
awesome reports.
Testing and validating REST services in Java is harder than it is in dynamic languages such as Ruby and Groovy. This is one more
domain.
The Rest-assured API is created so that you don’t necessarily need to be an HTTP expert.
If your team is made up mainly of Java coders, I highly recommend Rest-Assured for API testing.
Postman Email :
Automation with postMan: https://vyasarajvarappa.wordpress.com/2017/08/07/api-automation-using-postman/
Some folks don’t necessarily want to deal with coding in an IDE using the same language as their developers.
If you’re one of those people, you might want to consider Postman for some quick and dirty API testing without worrying abou
testing. But it’s also powerful enough that you can create more integrated solutions if you wish.
Postman is an easy-to-use Rest client and you can get started with it quickly leveraging its Chrome plugin. There’s also a native
It has a very rich interface that many Rest clients don’t have, making it easy to use. It also enables you to easily share your kno
responses and send it off to someone else so that they can take a look at it also.
Big Fish Games uses Postman as a collaborative tool. According to Amber Race, an SDET at the firm, they have one person who
Wiki so that anyone can run the API tests and ensure that what they’re doing doesn’t break existing API functionality. Postman
automatically kicks off your Postman tests.
If your team wants to not only test APIs but also have a tool to help automate some of your exploratory API testing efforts, Po
SoapUI
SoapUI has been around for a while now. If your teams are doing API testing only, and are composed mostly of QA engineers a
SoapUI is a fully functional test tool dedicated to API testing. Rather than having to create a solution from scratch, API allows y
If for some reason you need to create a custom workflow or functionality, you can code up your solution in SoapUI using Groo
If your team has complicated API testing scenarios and is made up of more QA/Test Engineers, SoapUI is the tool I would try fi
JMeter
Although JMeter was created for Load testing, many folks use it for functional API testing as well.
JMeter includes all the functionality you need to help test an API, plus some extra features that can be taken advantage of to e
For example, JMeter can automatically work with CSV files, which allows your teams to quickly create unique parameter value
your Continuous Integration pipelines.
If you plan on creating API functional tests you would also like to leverage in your performance tests, why not kill two birds wi
KarateDSL
KarateDSL, which is pretty new, makes creating scenarios for API-based Behavior Driven Development (BDD )tests really simpl
step definitions. The reason for that is that Karate has already created all the step definitions you need in order to get started
If you’re into newer technology and your team is already using Java and Cucumber, then KarateDSL might be the perfect choic
https://github.com/intuit/karate
https://www.testingexcellence.com/automated-api-testing-made-easy-karate/
SOAP UI tool was initially built for testing SOAP services. Then it is extended to RESTful web services. For a new users it might
Whereas Postman tool is built for testing REST APIs. It is very easy and nice user interface. It offers lots of functionality especia
are parsed properly based on the response type (JSON, XML or HTML). I personally vote for Postman
SoapUI is heavy tool and it is used for both rest and soap API’s. Postman is light weight tool and it comes with chrome plugin t
If you want to test web services without heavy weight SoapUI or JMeter, Postman is the solution.
It is the most used REST client worldwide.
Postman is available as a native app for Windows (X32, X64), Mac and Linux (X32, X64). You can download it from here. https:/
Native app has option to prevent request from being redirected automatically in case of 300-series response without Intercep
REST stands for Representational State Transfer, a term coined by Roy Fielding in 2000. It is an architecture style for designing
Architectural Constraints
Uniform interface: As the constraint name itself applies, you MUST decide APIs interface for resources inside system which ar
Client–server: This essentially means that client application and server application MUST be able to evolve separately without
Stateless: Make all client-server interaction stateless. Server will not store anything about latest HTTP request client made. It w
If client application need to be a stateful application for end user, where user logs in once and do other authorized operations
service the request – including authentication and authorization details.
Cacheable: In today’s world, caching of data and responses is of utmost important wherever they are applicable/possible. The
improvement for client side, and better scope for scalability for server because load has reduced.
In REST, caching shall be applied on resources when applicable and then these resources MUST declare themselves cacheable
Layered system: REST allow you to use a layered system architecture where you deploy the APIs on server A, and store data o
whether it is connected directly to the end server, or to an intermediary along the way.
Using RESTful APIs, you can do the same thing with your web services what you do to web pages.
The protocol is client/server, stateless, layered, and supports caching
What does Representational State Transfer mean? Transferring, accessing, and manipulating textual data representations in a
When deployed correctly, it provides a uniform interoperability, between different applications on the internet.
GET:
A GET request is the most common verb on the Web. A GET request transfers representations of named resources from a serv
requesting, the request returns a byte stream tagged with metadata, indicating how the client should interpret the resource.
One of the key points about the GET request is that it should not modify anything on the server side. It is fundamentally a safe
the safety of a GET request allows it to be cached.
POST is used when the client cannot predict the identity of the resource it is requesting to be created. When we hire people, p
creating.
https://github.com/rest-assured/rest-assured/wiki/usage
https://www.programcreek.com/java-api-examples/?api=com.jayway.restassured.path.json.JsonPath
Response response =
given().
param("param_name", "param_value").
when().
get("/title").
then().
contentType(JSON).
body("title", equalTo("My Title")).
extract().
response();
Use libraries
Rest-Assured to fluently create HTTP requests and assertions about the response.
AssertJ to create fluent, typesafe and readable assertions.
JsonPath (integrated into rest-assured) to easily navigate through JSON for simple checks (but generally prefer POJOs).
Awaitility to deal with asynchronous behavior.
Object mapper (like Jackson) to map between POJOs and JSON.
OkHttp MockWebServer to test REST clients.
https://blog.philipphauer.de/testing-restful-services-java-best-practices/
Create a RequestSpecification to reuse request configurations (base URL, parameters, content type, debugging logging) that yo
BeforeClass
public static void initSpec(){
spec = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setBaseUri("http://localhost:8080/")
.addFilter(new ResponseLoggingFilter())//log request and response for better debugging. You can also only log if a requ
.addFilter(new RequestLoggingFilter())
.build();
Don’t fiddle with string concatenation or the cumbersome JsonObject to create JSON for a request or to check the responded
Instead, create a separate POJO class and let an ObjectMapper like Jackson do the deserialization and serialization for you. Re
public class BlogDTO {
private String name;
private String description;
private String url;
//let your IDE generate the getters and fluent setters for your:
public BlogDTO setName(String name) {
this.name = name;
return this;
}
public BlogDTO setDescription(String description) {
this.description = description;
return this; }
public BlogDTO setUrl(String url) {
this.url = url;
return this;
}
Afterwards, you can use the fluent setters to write readable and typesafe code for creating test data.
assertThat(retrievedBlog.getName()).isEqualTo(newBlog.getName());
assertThat(retrievedBlog.getDescription()).isEqualTo(newBlog.getDescription());
assertThat(retrievedBlog.getUrl()).isEqualTo(newBlog.getUrl());
assertThat(retrievedEntity).isEqualToIgnoringGivenFields(expectedEntity, "id");
Also check out the method isEqualToIgnoringNullFields().
Create Tailored POJOs
Only add the necessary fields to the POJO. The service returns a JSON with 20 properties but you are only interested in two of
class and Jackson won’t bother if there are more JSON properties in the response than fields in your POJO.
JsonIgnoreProperties(ignoreUnknown = true)
public class BlogDTO {
private String name;
//the other JSON properties are not relevant for the test
//...
}
Alternatively, you can set this configuration globally to the ObjectMapper:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
What is API?
API stands for Application Programming Interface. It comprises of a set of functions that can be accessed and executed by ano
and establishes their interaction and data exchange.
In the modern development world, many web applications are designed based on 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 is stored and retrieved from a Database. (DB)
We can test UI with GUI testing tools and we can test logic tier (API) with API testing tools. Logic tier comprises of all of the bu
tier is called as API Testing.
API testing tests 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 diffi
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 sen
REST APIs or SOAP web services with JSON or XML message payloads being sent over HTTP, HTTPS, JMS, and MQ.
An example of this arrangement is REST-based interactions all communicate their status using standard HTTP status codes.
So, a 404 means a requested resource wasn't found;
a 401 code means the request wasn't authorized;
a 200 code means everything is OK;
and a 500 means there was an unrecoverable application error on the server.
REST is an architectural style to design systems like the Web. The main defining characteristic of REST are the four rules of the
Rule 1: Offer access through resources.
Rule 2: Represent resources by representations.
Rule 3: Exchange self-descriptive messages.
Rule 4: Connect resources through links.
Disadvantages of REST
The benefit of REST using HTTP constructs also creates restrictions, however. Many of the limitations of HTTP likewise turn int
based information between request-response cycles, which means REST-based applications must be stateless and any state m
SOAP relies heavily on XML, and together with schemas, defines a very strongly typed messaging framework. Every operation
response for that operation. Each input parameter is similarly defined and bound to a type: for example, an integer, a string, o
Description (or Definition, in later versions) Language. The WSDL is often explained as a contract between the provider and th
SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifica
What is Rest Assured?
In order to test REST APIs, I found REST Assured library so useful. It is developed by JayWay Company and it is a really powerfu
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.9.0</version>
<scope>test</scope>
</dependency>
import com.jayway.restassured.http.ContentType;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
given()
.when()
.get("http://d55csfapp05/IntuitionAPI/api/template/doc1")
.then()
.statusCode(200)
.and()
.contentType(ContentType.JSON)
.and()
.body(containsString("Designer 17.0.0"));
given()
.contentType("application/json")
.body(validJson)
.when().put("http://d55csfapp05/IntuitionAPI/api/realtime/doc3").then()
.statusCode(200)
.and()
.body(containsString("SampleField1"));
REST Assured is a Java library for validation of REST web services. It offers a friendly DSL (Domain specific Languages) that desc
follows the BDD paradigm, making tests very readable.
Most applications today expose their API as a set of HTTP endpoints that send and receive JSON data.
Making sure that these HTTP endpoints work according to the specifications is an essential requirement
The fact that the application under test is written in Java is irrelevant to REST Assured. REST Assured bases its tests only on JSO
REST Assured works on top of JUnit, therefore JUnit knowledge is essential.
Hamcrest knowledge is helpful but not required as we will only use some basic Hamcrest matchers.
Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively.
instead of using JUnit's assertEquals methods, we use Hamcrest's assertThat construct
REST Assured works on top of JUnit and therefore assumes that it's installed. Hamcrest Matchers are optional, and are not str
Gson is automatically used by REST Assured for JSON (de)serialization
REST Assured also supports XML
Verify
Status Code : given().when().get("/garage").then().statusCode(200);
Json:
{
"name":"Acme garage",
"info":{
"slots":150,
"status":"open"
}
}
Body:
The simplest way to test the body of a network response is by using string comparison. The body() method is provided by REST
comes from Hamcrest and makes the test pass (or fail) if the body contains that string.
given().when().get("/garage").then().body(containsString("Acme garage"));
given().when().get("/garage").then().body("name",equalTo("Acme garage"));
given().when().get("/garage").then().body("info.slots",equalTo(150)).body("info.status",equalTo("open"));
given().when().get("/garage").then().body("name",equalTo("Acme garage")).body("info.slots",equalTo(150)).body("info.status
given().contentType("application/json").body(car).when().post("/garage/slots").then().statusCode(200);
given().contentType("application/json").body(car).when().post("/garage/slots").then().body("empty",equalTo(false)).body("po
For bigger JSON objects, an alternative solution would be to directly use a Java object. This makes the intent of the test very cl
given()
.contentType("application/json")
.body(car)
.when().post("/garage/slots").then()
.body("empty",equalTo(false))
.body("position",lessThan(150));
REST Assured can deserialize JSON data to Java objects in a similar manner:
Again, we define a new Java object from the return result:
public class Slot {
REST Assured can extract information from a response while still verifying the call on its own.
int positionTakenInGarage = given().contentType("application/json").body(car).when().post("/garage/slots").then().body("emp
given().pathParam("slotID", positionTakenInGarage).when().delete("/garage/slots/{slotID}").then().statusCode(200);
Hamcrest comes with a library of useful matchers. Here are some of the most important ones.
Core
anything - always matches, useful if you don't care what the object under test is
describedAs - decorator to adding custom failure description
is - decorator to improve readability - see "Sugar", below
Logical
allOf - matches if all matchers match, short circuits (like Java &&)
anyOf - matches if any matchers match, short circuits (like Java ||)
not - matches if the wrapped matcher doesn't match and vice versa
Object
equalTo - test object equality using Object.equals
hasToString - test Object.toString
instanceOf, isCompatibleType - test type
notNullValue, nullValue - test for null
sameInstance - test object identity
Beans
hasProperty - test JavaBeans properties
Collections
array - test an array's elements against an array of matchers
hasEntry, hasKey, hasValue - test a map contains an entry, key or value
hasItem, hasItems - test a collection contains elements
hasItemInArray - test an array contains an element
Number
closeTo - test floating point values are close to a given value
greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering
Text
equalToIgnoringCase - test string equality ignoring case
equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
containsString, endsWith, startsWith - test string matching
https://techbeacon.com/how-perform-api-testing-rest-assured
http://www.baeldung.com/rest-assured-tutorial
https://github.com/rest-assured/rest-assured/blob/master/examples/rest-assured-itest-java/src/test/java/io/restassured/ites
https://github.com/rest-assured/rest-assured/tree/master/examples/rest-assured-itest-java/src/test/java/io/restassured/ites
https://www.swtestacademy.com/api-testing-with-rest-assured/
http://toolsqa.com/rest-assured/rest-assured-test/
http://rest-assured.io/
https://github.com/rest-assured/rest-assured/wiki/GettingStarted
https://github.com/rest-assured/rest-assured/wiki/Usage
https://github.com/rest-assured/rest-assured/wiki/usage#parameters
REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for REST
given().
auth().
preemptive().
basic("username", "password").
when().
get("http://path.to/basic/secured/api").
then().
assertThat().
statusCode(200);
}
given().
auth().
oauth2(YOUR_AUTHENTICATION_TOKEN_GOES_HERE).
when().
get("http://path.to/oath2/secured/api").
then().
assertThat().
statusCode(200);
}
given().
when().
get("http://ergast.com/api/f1/2017/circuits.json").
then().
assertThat().
spec(checkStatusCodeAndContentType).
and().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(20));
}
floating point numbers in JSON responses are mapped to primitive type float.
special charachers in url: https://www.werockyourweb.com/url-escape-characters/
http://restservicestesting.blogspot.com/2016/10/logging-in-rest-assured-request-logging.html
@Test
public void test_get_all_documents_in_wip()
{
given()
.log().all()
.get("http://localhost:80/IntuitionApi/api/States")
.then()
.log().all()
.and()
.statusCode(200)
.contentType(ContentType.JSON)
.body(containsString("SampleDocumentInitialControls"))
.body(containsString("{9416FB1F-1DB2-427D-8F5F-24EEC962BB28}"));
}
@Test
public void test_get_document_by_name_in_wip()
{
given()
// .pathParam("documentName", "%7B9416FB1F-1DB2-427D-8F5F-24EEC962BB28%7D")
.urlEncodingEnabled(false)
// .get("{documentName}")
.get(documentNameTest)
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body(containsString("SampleDocumentInitialControls"))
.body(containsString("{9416FB1F-1DB2-427D-8F5F-24EEC962BB28}"))
.body(containsString("html"));
}
https://www.journaldev.com/2321/gson-example-tutorial-parse-json
http://www.appsdeveloperblog.com/java-into-json-json-into-java-all-possible-examples/
https://futurestud.io/tutorials/gson-mapping-of-arrays-and-lists-of-objects
https://www.leveluplunch.com/java/examples/convert-json-array-to-arraylist-gson/
http://www.javainterviewpoint.com/read-write-json-using-gson/
http://javarevisited.blogspot.in/2013/04/convert-json-array-to-string-array-list-java-from.html
http://findnerd.com/list/view/How-to-Parse-and-read-the-JSON-Array-using-GSON-library/7266/
https://www.journaldev.com/2321/gson-example-tutorial-parse-json
https://futurestud.io/tutorials/gson-mapping-of-arrays-and-lists-of-objects
https://www.leveluplunch.com/java/examples/convert-json-array-to-arraylist-gson/
http://blog.nkdroidsolutions.com/how-to-parsing-json-array-using-gson-in-android-tutorial/
https://coderanch.com/t/674356/java/read-JSON-files-Gson
http://www.javainterviewpoint.com/read-write-json-using-gson/
http://javarevisited.blogspot.in/2013/04/convert-json-array-to-string-array-list-java-from.html
http://javarevisited.blogspot.in/2013/02/how-to-convert-json-string-to-java-object-jackson-example-tutorial.html#axzz4j841d
http://www.java67.com/2017/05/how-to-convert-java-object-to-json-using-Gson-example-tutorial.html
JSON Values
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
In JSON, string values must be written with double quotes: { "name":"John" }
JSON Files
The file type for JSON files is ".json"
The MIME type for JSON text is "application/json"
JSON Objects
Values in JSON can be objects.
{
"employee":{ "name":"John", "age":30, "city":"New York" }
}
JSON Arrays
Values in JSON can be arrays.
{
"employees":[ "John", "Anna", "Peter" ]
}
JSON Booleans
Values in JSON can be true/false.
{ "sale":true }
JSON null
Values in JSON can be null.
{ "middlename":null }
JSON Objects:
{ "name":"John", "age":30, "car":null }
JsonObject VS POJO
It really depends on the situation and the nature of your application. If the data your are receiving has no fixed structure/field
On the other hand, if it is of fixed structure and involves operations which access the fields, its better to go with pojo. It has be
http://www.jsonschema2pojo.org/
http://pojo.sodhanalibrary.com/
https://reqres.in/
Create a RequestSpecification to reuse request configurations (base URL, parameters, content type, logging, session keys) tha
Create a separate POJO (Plain Old Java Object) class and use an ObjectMapper like Jackson to serialize Java objects into JSON a
mapping. It is very useful to make a POST call.
The returned POJO’s can be validated by using Hamcrest matcher, but one can also use AssertJ library to write fluent, readable
a JSON response, creating a POJO class for mapping is a little bit of an overkill. Moreover, Rest Assured has a built-in support fo
For an asynchronous event to take effect, users must poll until a certain condition becomes true. We can use Awaitility which
example, posting a comment on FB and validating based on commentID.