Skip to main content

GET STARTED

Examples

Learn Karate through practical, real-world examples that demonstrate core concepts and best practices.

Basic API Test

A simple REST API test example:

Feature: Users API

Background: * url 'https://jsonplaceholder.typicode.com'

Scenario: Get user by id
Given path 'users', 1
When method get
Then status 200
And match response.name == 'Leanne Graham'
And match response.email == 'Sincere@april.biz'

POST Request with JSON

Creating a resource with JSON payload:

Scenario: Create a new post
Given path 'posts'
And request { title: 'Test Post', body: 'Test Content', userId: 1 }
When method post
Then status 201
And match response.title == 'Test Post'
And match response.id == '#number'

Data-Driven Testing

Using a data table for multiple test cases:

Scenario Outline: Verify user emails
Given path 'users', <id>
When method get
Then status 200
And match response.email == '<email>'

Examples:
| id | email |
| 1 | Sincere@april.biz |
| 2 | Shanna@melissa.tv |
| 3 | Nathan@yesenia.net |

Response Validation

Advanced response matching:

Scenario: Validate user structure
Given path 'users', 1
When method get
Then status 200
And match response ==
"""
{
id: '#number',
name: '#string',
username: '#string',
email: '#regex [a-z]+@[a-z]+.[a-z]+',
address: {
street: '#string',
suite: '#string',
city: '#string',
zipcode: '#regex [0-9]{5}-[0-9]{4}',
geo: {
lat: '#string',
lng: '#string'
}
},
phone: '#regex .*',
website: '#string',
company: '#object'
}
"""

Reusable Features

Calling another feature file:

Feature: Order Processing

Background:

* def authToken = call read('classpath:auth/get-token.feature')
_ header Authorization = 'Bearer ' + authToken.response.token

Scenario: Create and verify order

* def createOrder = call read('classpath:orders/create-order.feature')
* def orderId = createOrder.response.id

Given path 'orders', orderId
When method get
Then status 200
And match response.status == 'PENDING'

Working with Headers

Managing request headers:

Scenario: API call with custom headers
Given url 'https://api.example.com'
And path 'secure/data'
And header Accept = 'application/json'
And header X-API-Key = 'your-api-key'
And header User-Agent = 'Karate/1.0'
When method get
Then status 200

File Upload

Multipart file upload example:

Scenario: Upload a document
Given url 'https://api.example.com/upload'
And multipart file document = { read: 'classpath:files/sample.pdf', filename: 'sample.pdf' }
And multipart field description = 'Test document'
When method post
Then status 200
And match response.message == 'File uploaded successfully'

Retry Until

Polling for status changes:

Scenario: Wait for processing to complete
Given path 'jobs', jobId
And retry until responseStatus == 200 && response.status == 'COMPLETED'
When method get
Then match response.result == '#notnull'

Next Steps