Introduction to Path and Query Parameters

Welcome to another lesson of this course. In our previous lessons, we established a foundation by learning about RESTful APIs and making GET requests in Kotlin. Now, we will shift our focus to path and query parameters, essential tools for refining API requests and fetching specific data.

Path and query parameters play a crucial role in making your API requests more precise and efficient. Imagine you are shopping online: selecting a specific item using its ID is akin to a path parameter, while filtering items by categories like price or color resembles query parameters. In this lesson, we'll explore these concepts with practical examples, empowering you to extract just the information you need from an API.

Understanding Path Parameters

Path parameters are part of the URL used to access specific resources within an API, acting like unique identifiers. For example, if you want to retrieve a to-do item with ID 3, the URL would be structured as follows:

Plain text
1http://localhost:8000/todos/3

In this case, 3 is the path parameter specifying the particular item you wish to access.

Understanding Query Parameters

Query parameters are added to the URL after a ? to filter or modify the data returned by the API. They are formatted as key-value pairs. For instance, if you want to list only the completed to-do tasks, your request would be:

Plain text
1http://localhost:8000/todos?done=true

Here, done=true is the query parameter filtering the results to include only tasks that are marked as completed. Query parameters are usually case-sensitive, meaning done=true and Done=true might be treated differently by some APIs. Be consistent with parameter names and values to avoid unexpected filtering issues.

When using multiple query parameters in a URL, they should be separated by an ampersand &. Each query parameter is a key-value pair formatted as key=value. For example, if you want to both filter completed tasks and limit the results to the first 10, your URL might look like this:

Plain text
1http://localhost:8000/todos?done=true&limit=10

In this case, done=true and limit=10 are the query parameters, and they are separated by an & to indicate that both conditions should be applied to the API request.

Fetching Data with Path Parameters

Path parameters are used to target specific resources within an API, allowing you to access individual items directly. They are appended directly to the endpoint URL. For instance, if you want to fetch details of a specific to-do item using its ID, you'd use a path parameter.

Here's a practical example using ID 3 with the OkHttp library in Kotlin:

Kotlin
1import okhttp3.OkHttpClient 2import okhttp3.Request 3 4fun main() { 5 val client = OkHttpClient() 6 7 // Define the ID of the todo item you want to retrieve 8 val todoId = 3 9 10 // Build the request with the path parameter 11 val request = Request.Builder() 12 .url("http://localhost:8000/todos/$todoId") 13 .build() 14 15 // Make the GET request 16 client.newCall(request).execute().use { response -> 17 if (response.isSuccessful) { 18 // Parse and print the JSON response 19 response.body?.string()?.let { responseData -> 20 println(responseData) 21 } 22 } else { 23 println("Error fetching the todo with path parameter") 24 println("Status Code: ${response.code}") 25 } 26 } 27}

In this example, the todoId is a path parameter specifying the to-do item with ID 3. If successful, the task details will be displayed in the console.

Filtering Data with Query Parameters

Query parameters are attached to the URL to filter or modify the results returned by the API. They're especially useful for searching or narrowing down data without altering the overall resource structure.

Let's filter the to-do items to list only those marked as done using Kotlin:

Kotlin
1import okhttp3.OkHttpClient 2import okhttp3.Request 3 4fun main() { 5 val client = OkHttpClient() 6 7 // Construct the URL with query parameters manually 8 val url = "http://localhost:8000/todos?done=true" 9 10 // Build the request 11 val request = Request.Builder() 12 .url(url) 13 .build() 14 15 // Make the GET request 16 client.newCall(request).execute().use { response -> 17 if (response.isSuccessful) { 18 // Parse and print the JSON response 19 response.body?.string()?.let { responseData -> 20 println(responseData) 21 } 22 } else { 23 println("Error fetching todos with query parameter") 24 println("Status Code: ${response.code}") 25 } 26 } 27}

With this approach, the query parameter done=true is used to filter the results, focusing only on completed tasks.

Using Multiple Query Parameters

To refine data retrieval further, you can combine multiple query parameters. For instance, you might want to fetch to-do items that are marked as done and also have titles that start with a specific prefix.

Here's how you can filter to-do items that are completed and have titles starting with the prefix "c" in Kotlin:

Kotlin
1import okhttp3.OkHttpClient 2import okhttp3.Request 3import okhttp3.HttpUrl 4 5fun main() { 6 val client = OkHttpClient() 7 8 // Define the multiple query parameters 9 val url = HttpUrl.Builder() 10 .scheme("http") 11 .host("localhost") 12 .port(8000) 13 .addPathSegment("todos") 14 .addQueryParameter("done", "true") 15 .addQueryParameter("title", "c") 16 .build() 17 18 // Build the request 19 val request = Request.Builder() 20 .url(url) 21 .build() 22 23 // Make the GET request 24 client.newCall(request).execute().use { response -> 25 if (response.isSuccessful) { 26 // Parse and print the JSON response 27 response.body?.string()?.let { responseData -> 28 println(responseData) 29 } 30 } else { 31 println("Error fetching todos with multiple query parameters") 32 println("Status Code: ${response.code}") 33 } 34 } 35}

In this example, the HttpUrl.Builder is utilized to construct the URL by adding multiple query parameters. The Request.Builder then uses this URL to build the request, enabling efficient filtering of results based on the specified parameters.

Summary and Preparing for Practice

In this lesson, you’ve learned how to work with both path and query parameters to refine API requests. Path parameters allow you to pinpoint specific resources, whereas query parameters tailor the results based on defined conditions. Together, they provide a robust mechanism for fetching targeted and detailed information from an API.

You are now prepared to tackle the practice exercises, where you will apply these concepts and explore variations to reinforce your understanding. As you proceed, remember how these skills can be essential for effective API interaction, laying the groundwork for more advanced operations in future lessons. Keep up the momentum as you continue to advance through the course!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal