Lesson 3
Introduction to Path and Query Parameters in Go
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 using Go's standard library. 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 in Go, 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.

Setup Recap

Before jumping into implementing these parameters using Go, let's make sure everything's set up. Start by importing the necessary packages and defining the base URL:

Go
1package main 2 3import ( 4 "fmt" 5 "net/http" 6 "io" 7 "log" 8) 9 10// Base URL for the API 11const baseURL = "http://localhost:8000" 12 13func main() { 14 // Entry point 15}

Now we're all set to dive into the code examples!

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:

Go
1func fetchTodoByID(todoID int) { 2 url := fmt.Sprintf("%s/todos/%d", baseURL, todoID) 3 4 resp, err := http.Get(url) 5 if err != nil { 6 log.Fatalf("Error fetching the todo with path parameter: %v", err) 7 } 8 9 if resp.StatusCode == http.StatusOK { 10 data, _ := io.ReadAll(resp.Body) 11 fmt.Printf("Todo Item: %s\n", data) 12 } else { 13 log.Printf("Failed to fetch todo. Status Code: %d", resp.StatusCode) 14 } 15} 16 17func main() { 18 fetchTodoByID(3) 19}

In this example, todoID is a path parameter specifying the to-do item with ID 3. If successful, the function prints the details of that specific item. This demonstrates how path parameters enable you to access individual resources accurately.

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:

Go
1func fetchCompletedTodos() { 2 url := fmt.Sprintf("%s/todos?done=true", baseURL) 3 4 resp, err := http.Get(url) 5 if err != nil { 6 log.Fatalf("Error fetching todos with query parameter: %v", err) 7 } 8 9 if resp.StatusCode == http.StatusOK { 10 data, _ := io.ReadAll(resp.Body) 11 fmt.Printf("Completed Todos: %s\n", data) 12 } else { 13 log.Printf("Failed to fetch todos. Status Code: %d", resp.StatusCode) 14 } 15} 16 17func main() { 18 fetchCompletedTodos() 19}

Here, the query parameter done=true is used to filter the results. The function focuses only on completed tasks, demonstrating how query parameters can streamline outputs by highlighting specific criteria.

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":

Go
1func fetchFilteredTodos(doneStatus, titlePrefix string) { 2 url := fmt.Sprintf("%s/todos?done=%s&title=%s", baseURL, doneStatus, titlePrefix) 3 4 resp, err := http.Get(url) 5 if err != nil { 6 log.Fatalf("Error fetching todos with multiple query parameters: %v", err) 7 } 8 9 if resp.StatusCode == http.StatusOK { 10 data, _ := io.ReadAll(resp.Body) 11 fmt.Printf("Filtered Todos: %s\n", data) 12 } else { 13 log.Printf("Failed to fetch todos. Status Code: %d", resp.StatusCode) 14 } 15} 16 17func main() { 18 fetchFilteredTodos("true", "c") 19}

In this example, the query parameters done=true and title=c are used together to filter the results. If successful, the function retrieves items that are both completed and begin with "c".

Summary and Preparing for Practice

In this lesson, you’ve learned how to work with both path and query parameters to refine API requests in Go. 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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.