0% found this document useful (0 votes)
59 views81 pages

Rest Assured Workshop

The document provides an overview of testing RESTful APIs using REST Assured. It discusses REST concepts like HTTP methods, resources and parameters, requests and responses. It also demonstrates how to write API tests using REST Assured including making requests, validating responses, and logging data. Hands-on exercises are provided to test a sample banking API.

Uploaded by

gchidamb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views81 pages

Rest Assured Workshop

The document provides an overview of testing RESTful APIs using REST Assured. It discusses REST concepts like HTTP methods, resources and parameters, requests and responses. It also demonstrates how to write API tests using REST Assured including making requests, validating responses, and logging data. Hands-on exercises are provided to test a sample banking API.

Uploaded by

gchidamb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Test the REST

Testing RESTful web services using REST Assured

An open source workshop by …

Originally created by Bas Dijkstra – [email protected] – https://www.ontestautomation.com


What are we going to do?
_RESTful APIs

_REST Assured

_Hands-on exercises
Preparation
_Install a recent JDK (17)

_Install IntelliJ (or any other IDE)

_Import Maven project into your IDE


_ https://github.com/basdijkstra/rest-assured-workshop
(RESTful) APIs are
commonly used to
exchange data between
two parties
request

API API
consumer provider
response

System System
A REST API request

HTTP method Resource (URI) and parameters

Request headers

Request body
HTTP Resource (URI) and
method parameters

Request headers

Request body
HTTP methods
_GET, POST, PUT, PATCH, DELETE, OPTIONS, …

_CRUD operations on data


POST Create
GET Read
PUT / PATCH Update
DELETE Delete
… …

_Conventions, not standards!


HTTP Resource (URI) and

Resources and
method parameters

Request headers

Request body
parameters
_Uniform Resource Identifier

_Uniquely identifies the resource to operate on

_Can contain parameters


_ Query parameters
_ Path parameters
HTTP Resource (URI) and

Resources and
method parameters

Request headers

Request body
parameters
_Path parameters
_ http://api.zippopotam.us/us/90210
_ http://api.zippopotam.us/ca/B2A

_Query parameters
_ http://md5.jsontest.com/?text=testcaseOne
_ http://md5.jsontest.com/?text=testcaseTwo

_There is no official standard!


HTTP Resource (URI) and
method parameters

Request headers

Request body
Request headers
_Key-value pairs

_Can contain metadata about the request body


_ Content-Type (what data format is the request body in?)
_ Accept (what data format would I like the response body
to be in?)
_…

_Can contain session and authorization data


_ Cookies
_ Authorization tokens
_…
HTTP Resource (URI) and

Authorization: Basic
method parameters

Request headers

Request body

_Username and password sent with every request

_Base64 encoded (not really secure!)

_Ex: username = aladdin and password = opensesame

Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l


HTTP Resource (URI) and

Authorization: Bearer
method parameters

Request headers

Request body

_Token with limited validity is obtained first

_Token is then sent with all subsequent requests

_Most common mechanism is OAuth(2)

_JWT is a common token format

Authorization: Bearer RsT5OjbzRn430zqMLgV3Ia


HTTP Resource (URI) and
method parameters

Request headers

Request body
Request body
_Data to be sent to the provider

_REST does not prescribe a specific data format

_Most common:
_ JSON
_ XML
_ Plain text

_Other data formats can be sent using REST, too


A REST API response

HTTP status code

Response headers

Response body
HTTP status code

Response headers

Response body
HTTP status code
_Indicates result of request processing by provider

_Five different categories

_1XX Informational 100 Continue


_2XX Success 200 OK
_3XX Redirection 301 Moved Permanently
_4XX Client errors 400 Bad Request
_5XX Server errors 503 Service Unavailable
HTTP status code

Response headers

Response body
Response headers
_Key-value pairs

_Can contain metadata about the response body


_ Content-Type (what data format is the response body in?)
_ Content-Length (how many bytes in the response body?)

_Can contain provider-specific data


_ Caching-related headers
_ Information about the server type
HTTP status code

Response headers

Response body
Response body
_Data returned by the provider

_REST does not prescribe a specific data format

_Most common:
_ JSON
_ XML
_ Plain text

_Other data formats can be sent using REST, too


An example
_GET http://ergast.com/api/f1/2018/drivers.json
Where are APIs used?

Mobile Internet of API economy


Things
Where are APIs used?

Web Microservices
applications architectures
Why I ♥ testing at the API level
_Tests run much faster than UI-driven tests

_Tests are much more stable than UI-driven tests

_Tests have a broader scope than unit tests

_Business logic is often exposed at the API level


Tools for testing RESTful APIs
_Free / open source
_ Postman
_ SoapUI
_ Code libraries like REST Assured, RestSharp, requests
_…

_Commercial
_ Parasoft SOAtest
_ SoapUI Pro
_…

_Build your own (using HTTP libraries for your


language of choice)
REST Assured
_Java DSL for writing tests for RESTful APIs

_Removes a lot of boilerplate code

_Runs on top of common unit testing frameworks


_ JUnit, TestNG

_Developed and maintained by Johan Haleby


Configuring REST Assured
_Download from http://rest-assured.io

_Add as a dependency to your project


_ Maven
_ Gradle
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.1.1</version>
<scope>test</scope>
</dependency>
REST Assured documentation
_Usage guide
_ https://github.com/rest-assured/rest-assured/wiki/Usage

_Links to other documentation (JavaDoc, getting


started, release notes)
_ http://rest-assured.io
A sample test
REST Assured uses JUnit (this could also be TestNG)

Make an HTTP GET call to retrieve data from the provider

Perform an assertion on the returned response (here: on the JSON response payload)
REST Assured features
_Support for all HTTP methods (GET, POST, PUT, …)
_Support for Gherkin (Given/When/Then)
_Use of Hamcrest matchers for checks (equalTo)
_Use of Jsonpath/GPath for selecting elements from
JSON response
About Hamcrest matchers
_Express expectations in natural language

_Examples:
equalTo(X) Does the object equal X?
hasItem(“Rome”) Does the collection contain an item “Rome”?
hasSize(3) Does the size of the collection equal 3?
not(equalTo(X)) Inverts matcher equalTo()

_ http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html
About GPath
_JsonPath is a query language for JSON documents
_ REST Assured uses the GPath implementation of JsonPath

_Similar aims and scope as XPath for XML

_Documentation and examples:


_ http://groovy-lang.org/processing-xml.html#_gpath
_ http://groovy.jmiguel.eu/groovy.codehaus.org/GPath.html
GPath example

body(“address.geo.lat”, equalTo(“-37.3159”));
Validating technical response
data
_HTTP status code
_Response Content-Type header
_Other headers and their value
_Cookies and their value
_…
Logging request data

log().all() after given() logs all request


data to the console

You can also use log().body(),


log().headers() as well as other options
Logging request data
Logging response data

log().all() after then() logs all response


data to the console

You can also use log().body(),


log().headers() as well as other options
Logging
response data
Our API under test
_(Simulation of) an online banking API

_Customer data (GET, POST)

_Account data (POST, GET)

_RESTful API
Demo
_How to use the test suite
_Executing your tests
_Reviewing test results
Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises1Test.java

_Simple checks
_ Validating individual elements
_ Validating collections and items therein
_ Validating technical response properties

_Stubs are predefined


_ Don’t worry about the references to http://localhost
_ You only need to write the tests using REST Assured

_Answers are in answers > RestAssuredAnswers1Test.java

_Examples are in examples > RestAssuredExamples.java


Parameters in RESTful web
services
_Path parameters
_ http://api.zippopotam.us/us/90210
_ http://api.zippopotam.us/ca/B2A

_Query parameters
_ http://md5.jsontest.com/?text=testcaseOne
_ http://md5.jsontest.com/?text=testcaseTwo

_There is no official standard!


Using query parameters
_GET http://md5.jsontest.com/?text=testcase

Define a query parameter and its value


Using path parameters
_ GET http://jsonplaceholder.typicode.com/users/1

Define a (custom) path parameter name and the parameter value

Define the location of the path parameter


using the chosen name between {}
Exchange data between consumer and provider

GET to retrieve data from provider, POST to


send data to provider, …

APIs are all about


data
Business logic and calculations often
exposed through APIs
Run the same test more than once…

… for different combinations of input and


expected output values

Parameterized testing
More efficient to do this at the API level…

… as compared to doing this at the UI level


‘Feeding’ test data to your test
Define test data in the @CsvSource
annotation (one record for every iteration,
parameters separated by commas)

Use parameters to pass the test


data values into the method

Use parameters in the test method where required


Running the data driven test

The test method is run


three times, once for
each array (‘test case’)
in the test data set
Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises2Test.java

_Data driven tests


_ Creating a test data object using @CsvSource
_ Using test data to call the right URI
_ Using test data in assertions

_Answers are in answers > RestAssuredAnswers2.java

_Examples are in examples > RestAssuredExamples.java


Authentication
_Securing web services

_Most common authentication schemes:

_ Basic authentication (username / password)

_ OAuth(2)
Basic authentication

Adding preemptive() makes REST


Assured send the credentials
directly, saving us from dealing with
the provider challenging mechanism
OAuth(2)

The authentication token is typically


retrieved prior to running the tests to
ensure that a valid token is used
Sharing variables between tests
_Example: uniquely generated IDs

_First call returns a unique ID (e.g. a new user ID)

_Second call needs to use this generated ID

_Since there’s no way to predict the ID, we need to


capture and reuse it
Sharing The return value can be

variables stored in a variable…

between
tests
path() takes a GPath
expression to extract
the required value

… and reused at a later point in time


RequestSpecifications
_Reuse shared properties shared by many calls

_Base URI

_Port

_Authentication data

_…
Defining and using
RequestSpecifications

… and use it by calling


spec() in the given()
section of your test

Build your RequestSpecification using the Builder pattern…


Sharing checks between tests
_Example: checking status code and MIME type for
all responses

_Another maintenance burden if specified


individually for each test

_What if we could specify this once and reuse


throughout our tests?
Using a
ResponseSpecification

Build your ResponseSpecification using the Builder pattern…

… and use it by calling


spec() in the then()
section of your test
Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises3Test.java

_Apply value reuse as shown in the slides


_Use basic and OAUth authentication schemes

_Answers are in answers > RestAssuredAnswers3Test.java

_Examples are in examples > RestAssuredExamples.java


XML support
_So far, we’ve only used REST Assured on APIs that
return JSON

_It works just as well with XML-based APIs

_Identification of response elements uses XmlPath


instead of JsonPath

_No need for additional configuration


_ REST Assured uses response content type header value to
determine how to process a response body
XmlPath – examples

Check country for the


first car in the list
XmlPath – examples

Check year for the


last car in the list
XmlPath – examples

Check model for the


second car in the list

(use an @ to refer to
an XML attribute)
XmlPath – examples

Check there’s one car from


Japan in the list

findAll is a filter operation


XmlPath – examples

Check that two cars have a


make starting with ‘A’

grep takes a regular


expression to search in a
list of values
Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises4Test.java

_Communicating with an API returning an XML document

_Use XmlPath to select the right nodes

_Use filters, in, grep() where needed

_Answers are in answers > RestAssuredAnswers4Test.java

_Examples are in examples > RestAssuredExamplesXml.java


(De-)serialization of POJOs
_REST Assured is able to convert POJO instances
directly to XML or JSON (and back)

_Useful when dealing with test data objects


_ Creating request body payloads
_ Processing response body payloads

_Requires additional libraries on the classpath


_ Jackson or Gson for JSON
_ JAXB for XML
Example: serialization
_POJO representing an address
Example: serialization

Pass the object as a request body using body()…

… and REST Assured will serialize it to JSON using Jackson


(which means you can customize the field names if required)
Example: deserialization

… store the deserialized response payload


in an object of that type…

Perform response verifications as usual…

Specify the type to deserialize to using as()…

… and then use it in the remainder of your test method as required


Example: deserialization
(without initial checks)

… store the deserialized response payload


in an object of that type…

Specify the object type to deserialize to


using as()…

… and then use it in the remainder


of your test method as required
Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises5Test.java

_Practice (de-)serialization for yourself

_You don’t need to create or adapt the POJOs

_Answers are in answers > RestAssuredAnswers5Test.java

_Examples are in examples > RestAssuredExamples.java


The problem with
‘traditional’ REST APIs
Query language for APIs…

… as well as a runtime to fulfill them

GraphQL
“Ask for what you need,
and get exactly that”

https://graphql.org
request (query)
GraphQL GraphQL
API API
consumer provider
response (JSON)

System System
Create a valid GraphQL query…

… and send it in the request body (query)

Sending a GraphQL query


“Ask for what you need,
and get exactly that”
A Java

HashMap<String, Object>

structure is a good fit


for this situation
These are ‘regular’ REST responses, with…

… an HTTP status code, …

GraphQL API responses


… response headers…
… and a JSON response body
containing the requested data
Sending a basic GraphQL query
The query can be a simple (multiline) String

Initialize the GraphQL


query object…

… and send it as the request body

The response body is regular JSON,


so we know how to handle that already
Parameterizing GraphQL queries
GraphQL queries can be parameterized, too

Let’s create a test that queries


and verifies the weather for
three different cities

Initialize the GraphQL


query and set query
variable values…

… and send the


parameterized query to the
API endpoint
Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises6Test.java

_Working with the SpaceX GraphQL API


_Create a basic query, send it and verify the response
_Create a parameterized query and a data driven test,
create and send queries and verify the responses

_Answers are in answers > RestAssuredAnswers6Test.java

_ Examples are in examples > RestAssuredExamplesGraphQLTest.java


Now it’s your turn!
_ src > test > java > exercises > RestAssuredExercises7Test.java

_Capstone assignment

_Combines several concepts we have seen throughout this


workshop
_ Extracting values from responses
_ Deserialization
_ Using filters
_ Parameterization, assertions, …

_Answers are in answers > RestAssuredAnswers7Test.java


Contact
_Email: [email protected]

_Website: https://www.ontestautomation.com/training

_LinkedIn: https://www.linkedin.com/in/basdijkstra

You might also like