Hey there! If you’re working with API testing using Karate, you’ve probably encountered the need to send multiple parameters to your API endpoints. It’s a common requirement, and thankfully, Karate provides flexible and powerful ways to achieve this. Whether you’re dealing with query parameters, path parameters, or request bodies, Karate offers elegant solutions to manage and transmit various data types.
This guide will walk you through the different techniques to pass multiple parameters in Karate. We’ll explore various scenarios, from simple GET requests with query strings to complex POST requests with JSON payloads. I’ll break down each method with clear examples and explanations, ensuring you understand not just *how* to do it, but also *why* it’s done that way. Get ready to level up your Karate skills!
Understanding Parameter Types in Karate
Before we jump into the mechanics of passing parameters, let’s clarify the different types of parameters you’ll commonly encounter in API testing. Understanding these distinctions is crucial for choosing the right approach in your Karate feature files.
Query Parameters
Query parameters are appended to the URL after a question mark (?). They are typically used to filter, sort, or paginate data. For example, in the URL https://api.example.com/products?category=electronics&sort=price&order=asc, category, sort, and order are query parameters.
Path Parameters
Path parameters are part of the URL’s path itself. They are often used to identify specific resources. For example, in the URL https://api.example.com/products/123, 123 is a path parameter representing the product ID.
Request Body Parameters
Request body parameters are sent within the body of a request, typically in JSON or XML format. These are commonly used for POST, PUT, and PATCH requests to send data to the server. The format and structure of the body are defined by the API’s requirements.
Passing Query Parameters in Karate
Karate offers several straightforward methods for passing query parameters. Let’s explore them.
Using the `param` Keyword
The `param` keyword is the simplest and most direct way to add query parameters to your request. You can use it multiple times to add multiple parameters. The order of the parameters defined in your `.feature` file is the order they will appear in the URL.
Feature: Query Parameter Example
Scenario: Passing multiple query parameters
Given url 'https://reqres.in/api/users'
And param page = 2
And param per_page = 5
When method GET
Then status 200
And print response
In this example, we’re sending a GET request to https://reqres.in/api/users with the query parameters page=2 and per_page=5. Karate will automatically construct the URL as https://reqres.in/api/users?page=2&per_page=5.
Using a Map for Query Parameters
For more complex scenarios or when you have a large number of parameters, using a map (also known as a JSON object) is a cleaner and more organized approach. This method is particularly useful when the parameters are dynamically generated or read from a data source.
Feature: Query Parameter Example with Map
Scenario: Passing multiple query parameters using a map
Given url 'https://reqres.in/api/users'
And params {
page: 2,
per_page: 5,
sort: 'email'
}
When method GET
Then status 200
And print response
Here, we define a map containing the query parameters. The params keyword tells Karate to add these key-value pairs as query parameters to the URL. This approach improves readability, especially when dealing with many parameters.
Dynamically Generating Query Parameters
You might need to generate query parameters dynamically based on variables or data from a file. Karate’s variable substitution capabilities make this easy. This is particularly useful for building more flexible and reusable tests. (See Also: How To Unlock Chao Karate )
Feature: Dynamic Query Parameters
Scenario: Passing dynamic query parameters
* def pageSize = 10
* def sortBy = 'name'
Given url 'https://reqres.in/api/users'
And params {
page: 1,
per_page: #(pageSize),
sort: #(sortBy)
}
When method GET
Then status 200
And print response
In this example, we define variables pageSize and sortBy. We then use the #(variableName) syntax within the map to substitute the values of these variables into the query parameters. This allows you to easily change the parameters without modifying the core test logic.
Passing Path Parameters in Karate
Path parameters are integral to many REST APIs. Karate provides a clean way to define and use them.
Using the Url String with Placeholders
The simplest way to pass path parameters is to include placeholders in your URL string. Karate replaces these placeholders with the actual parameter values.
Feature: Path Parameter Example
Scenario: Passing a path parameter
* def userId = 123
Given url 'https://reqres.in/api/users/' + userId
When method GET
Then status 200
And print response
In this scenario, we use string concatenation to build the URL. The `userId` variable is concatenated with the base URL. This is a clear and effective way to define path parameters.
Using the `path` Keyword
The `path` keyword offers a more structured approach, especially when dealing with multiple path parameters. It can make your feature files easier to read and maintain.
Feature: Path Parameter Example with Path Keyword
Scenario: Passing multiple path parameters
* def userId = 123
* def resource = 'products'
Given url 'https://api.example.com'
And path resource, userId
When method GET
Then status 200
And print response
The `path` keyword takes a comma-separated list of values, which are appended to the base URL. This approach separates the URL definition from the parameter values, leading to better readability.
Combining Path and Query Parameters
You can seamlessly combine path and query parameters in your Karate tests. This combination is a common requirement in API testing.
Feature: Combining Path and Query Parameters
Scenario: Passing path and query parameters
* def userId = 123
Given url 'https://reqres.in/api/users/' + userId
And param page = 1
And param per_page = 10
When method GET
Then status 200
And print response
In this example, we use string concatenation for the path parameter (userId) and the `param` keyword for the query parameters (page and per_page). Karate handles the construction of the complete URL correctly.
Passing Request Body Parameters in Karate
Request body parameters are essential when working with POST, PUT, and PATCH requests. Karate supports various formats for sending request bodies, including JSON and XML.
Sending Json Payloads
JSON is the most prevalent format for exchanging data in modern APIs. Karate makes sending JSON payloads straightforward.
Feature: JSON Payload Example
Scenario: Sending a JSON payload
Given url 'https://reqres.in/api/users'
And request {
name: 'morpheus',
job: 'leader'
}
When method POST
Then status 201
And print response
In this example, the request keyword is used to define the JSON payload. Karate automatically sets the Content-Type header to application/json. The body of the request contains the JSON data to be sent.
(See Also:
Do Koreans Do Karate
)
Using Variables in Json Payloads
You can use variables within your JSON payloads to make your tests more dynamic.
Feature: JSON Payload with Variables
Scenario: Sending a JSON payload with variables
* def userName = 'John Doe'
* def userJob = 'Developer'
Given url 'https://reqres.in/api/users'
And request {
name: #(userName),
job: #(userJob)
}
When method POST
Then status 201
And print response
Here, we use variables userName and userJob within the JSON payload. Karate substitutes the values of these variables before sending the request. This is particularly useful for data-driven testing.
Sending Xml Payloads (less Common, but Supported)
While JSON is the dominant format, some APIs still use XML. Karate supports sending XML payloads as well. Note that you’ll need to set the correct `Content-Type` header.
Feature: XML Payload Example
Scenario: Sending an XML payload
Given url 'https://api.example.com/data'
And request '<data><name>John</name><value>100</value></data>'
And header Content-Type = 'application/xml'
When method POST
Then status 200
And print response
In this example, we define the XML payload as a string. The header keyword is used to set the Content-Type to application/xml, which is crucial for the server to correctly interpret the request body.
Using Data Tables for Request Bodies
For more complex data structures, data tables can be a valuable tool for defining request bodies, making tests more readable and maintainable.
Feature: Data Table for Request Body
Scenario: Sending a JSON payload using a data table
Given url 'https://reqres.in/api/users'
And request {
"name": "morpheus",
"job": "leader"
}
When method POST
Then status 201
And print response
Data tables in Karate can also be used to define JSON payloads, particularly when the structure is simple or when you want to make your tests more organized. While not as common for complex structures, they provide an alternative when readability is prioritized.
Advanced Techniques for Parameter Passing
Beyond the basics, Karate offers advanced features to handle more complex scenarios.
Using `form Fields` for Url Encoded Parameters
If your API expects URL-encoded form data (application/x-www-form-urlencoded), you can use the form fields keyword.
Feature: Form Fields Example
Scenario: Sending form fields
Given url 'https://api.example.com/login'
And form fields {
username: 'user',
password: 'password'
}
When method POST
Then status 200
And print response
This will send the parameters in the request body, encoded in the format expected by the server.
Parameterizing Headers
You can also parameterize headers, which is often crucial for authentication and authorization.
Feature: Header Parameterization
Scenario: Setting a header with a variable
* def apiKey = 'your_api_key'
Given url 'https://api.example.com/data'
And header Authorization = 'Bearer ' + apiKey
When method GET
Then status 200
And print response
In this example, the apiKey variable is used to set the Authorization header. This makes it easy to manage and update API keys or other header values.
(See Also:
How To Block Punches In Karate
)
Working with Files (multipart/form-Data)
For APIs that require file uploads, Karate supports multipart/form-data. This is often used for uploading images, documents, or other files.
Feature: File Upload Example
Scenario: Uploading a file
Given url 'https://api.example.com/upload'
And multipart file file = { read: 'classpath:test.png', filename: 'test.png', contentType: 'image/png' }
When method POST
Then status 200
And print response
The multipart file keyword is used to specify the file to be uploaded. You provide the file path, filename, and content type. This is a powerful feature for testing file upload functionality.
Using Karate’s Built-in Functions
Karate offers built-in functions that can be used to generate parameters dynamically. For instance, you can use uuid() to generate a unique identifier.
Feature: Using uuid() function
Scenario: Generating a UUID
* def userId = uuid()
Given url 'https://api.example.com/users'
And request { id: #(userId) }
When method POST
Then status 201
And print response
This demonstrates the generation of a unique user ID, useful for creating unique data during testing.
Best Practices and Tips
To write effective and maintainable Karate tests, consider these best practices:
- Organize your feature files: Structure your feature files logically, separating different API endpoints and test scenarios.
- Use variables and data tables: Leverage variables and data tables to make your tests more flexible and readable. This promotes reusability and reduces redundancy.
- Keep your tests concise: Avoid overly complex scenarios. Break down complex interactions into smaller, more manageable tests.
- Document your tests: Add comments to explain the purpose of your tests and the expected behavior. This helps with understanding and maintenance.
- Use assertions effectively: Verify the response status code, headers, and body to ensure the API behaves as expected.
- Utilize data-driven testing: When testing multiple scenarios with different data, consider using data-driven testing techniques.
Debugging Parameter Passing Issues
Sometimes, parameters don’t get passed correctly. Here’s how to troubleshoot issues:
- Print the request: Use
print requestto examine the complete request being sent, including headers and body. - Inspect the response: Examine the response status code, headers, and body to identify any errors.
- Check the server logs: Examine the server logs to see how the server is interpreting the request.
- Verify the content type: Ensure that the
Content-Typeheader is set correctly (e.g.,application/json,application/xml,application/x-www-form-urlencoded). - Use a proxy tool: Use a proxy tool (such as Charles Proxy or Fiddler) to intercept and inspect the HTTP traffic. This allows you to see exactly what is being sent and received.
Choosing the Right Approach
The best method for passing parameters depends on the specific API and the type of parameters you need to send. Here’s a quick guide:
| Parameter Type | Method | Example |
|---|---|---|
| Query Parameters (simple) | param keyword |
And param page = 1 |
| Query Parameters (multiple/dynamic) | params keyword with a map |
And params { page: 1, per_page: #(pageSize) } |
| Path Parameters | String concatenation or `path` keyword | Given url 'https://api.example.com/' + userId or And path 'products', productId |
| JSON Payload | request keyword |
And request { name: 'John', job: 'Developer' } |
| XML Payload | request keyword + header Content-Type = 'application/xml' |
And request '<data>...'And header Content-Type = 'application/xml' |
| URL Encoded Form Data | form fields keyword |
And form fields { username: 'user', password: 'password' } |
| Files (multipart/form-data) | multipart file keyword |
And multipart file file = { read: 'classpath:test.png', filename: 'test.png', contentType: 'image/png' } |
Final Thoughts
You’ve now explored various methods for passing multiple parameters in Karate. You’ve seen how to handle query parameters, path parameters, request bodies, and even file uploads. Remember that the key is to choose the approach that best suits your needs and makes your tests clear and maintainable.
By understanding these techniques and applying the best practices, you can create robust and reliable API tests using Karate. Keep practicing and experimenting with these methods to become proficient in building comprehensive test suites.
I encourage you to experiment with these examples, and modify them to suit your specific API testing needs. Happy testing!
