Welcome to another lesson of this course. In our previous lessons, we established a foundation by learning about RESTful APIs and making GET
requests with Dart's http
package. 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.
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 text1http://localhost:8000/todos/3
In this case, 3
is the path parameter specifying the particular item you wish to access.
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 text1http://localhost:8000/todos?done=true
Here, done=true
is the query parameter filtering the results to include only tasks that are marked as completed.
Before jumping into implementing these parameters using Dart's http
package, let's make sure everything's set up. Start by importing the http
package, convert
for JSON decoding, and ensure your main
function is marked as async
to handle asynchronous operations:
Dart1import 'dart:convert'; 2import 'package:http/http.dart' as http; 3 4void main() async { 5 // Base URL for the API 6 final String baseUrl = "http://localhost:8000"; 7 8 // Rest of the code... 9}
Now we're all set to dive into the code examples!
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:
Dart1// Define the ID of the todo item you want to retrieve 2final int todoId = 3; 3 4// Make a GET request using the path parameter for the specific todo item 5final response = await http.get(Uri.parse('$baseUrl/todos/$todoId')); 6 7// Check if the request was successful 8if (response.statusCode == 200) { 9 // Parse the JSON response to get details of the todo item 10 var todo = jsonDecode(response.body); 11 12 // Print all details of the todo item 13 print("ID: ${todo['id']}"); 14 print("Title: ${todo['title']}"); 15 print("Description: ${todo['description']}"); 16 print("Done: ${todo['done']}"); 17} else { 18 // Handle potential errors 19 print("Error fetching the todo with path parameter"); 20 print("Status Code: ${response.statusCode}"); 21 print("Error Details: ${response.body}"); 22}
In this example, the todoId
is a path parameter specifying the to-do item with ID 3, and the full URL looks like http://localhost:8000/todos/3
. If successful, you'll get an output displaying the task details:
Plain text1ID: 3 2Title: Finish project report 3Description: Summarize Q4 performance metrics 4Done: False
This output confirms that the specific item was retrieved, demonstrating how path parameters enable you to access individual resources accurately.
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:
Dart1// Fetch todos with a query parameter to filter for completed items 2final response = await http.get(Uri.parse('$baseUrl/todos?done=true')); 3 4// Check if the request was successful 5if (response.statusCode == 200) { 6 // Parse the JSON response to get the list of completed todos 7 List todos = jsonDecode(response.body); 8 9 // Print the todo items 10 for (var todo in todos) { 11 print("- ${todo['id']}: ${todo['title']}"); 12 } 13} else { 14 // Handle potential errors 15 print("Error fetching todos with query parameter"); 16 print("Status Code: ${response.statusCode}"); 17 print("Error Details: ${response.body}"); 18}
Here, the query parameter done=true
is used to filter the results. The full URL in this case looks like http://localhost:8000/todos?done=true
, focusing only on completed tasks. If successful, the output will list the tasks that are marked as done, emphasizing how query parameters can streamline outputs by highlighting specific criteria:
Plain text1- 2: Call mom 2- 4: Workout
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":
Dart1// Define the multiple query parameters using a map 2final Map<String, String> params = {"done": "true", "title": "c"}; 3 4// Use the replace method to add query parameters to the URL 5final response = await http.get(Uri.parse('$baseUrl/todos').replace(queryParameters: params)); 6 7// Check if the request was successful 8if (response.statusCode == 200) { 9 // Parse the JSON response to get the filtered list of todos 10 List todos = jsonDecode(response.body); 11 12 // Print the filtered todo items 13 for (var todo in todos) { 14 print("- ${todo['id']}: ${todo['title']}"); 15 } 16} else { 17 // Handle potential errors 18 print("Error fetching todos with multiple query parameters"); 19 print("Status Code: ${response.statusCode}"); 20 print("Error Details: ${response.body}"); 21}
In this example, the params
map is used to define multiple query parameters, where each key-value pair represents a parameter and its value. The replace
method is then used to append these query parameters to the base URL. The URL in this request will look like http://localhost:8000/todos?done=true&title=c
, retrieving items that are both completed and begin with "c". If successful, the output will be:
Plain text1- 2: Call mom
By using the params
map and the replace
method, you can efficiently manage and apply multiple query parameters to your API requests.
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 further 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!
