Working with REST APIs in Go: Fetching, Searching, Creating, Updating, and Deleting Data
When working with APIs, performing HTTP requests to fetch, create, update, or delete data is a common task. While JavaScript’s fetch
API makes these operations straightforward, Go provides its own set of tools to achieve similar results. We’ll explore how to perform these HTTP operations in Go using the net/http
package.
Fetching Data
To fetch data from a REST API, you can use the http.Get
function provided by the net/http
package. This function sends a GET request and returns a response.
Example: Fetching All Products
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
// Fetch all products
response, err := http.Get("https://dummyjson.com/products")
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var data map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&data); err != nil {
log.Fatal(err)
}
fmt.Println(data)
}
Explanation:
http.Get
sends a GET request to the specified URL.- The response body is read and decoded into a
map[string]interface{}
to handle the JSON data.
Example: Fetching Products with a Search Query
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
// Fetch products with a search query
response, err := http.Get("https://dummyjson.com/products/search?q=phone")
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var data map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&data); err != nil {
log.Fatal(err)
}
fmt.Println(data)
}
Explanation:
- The query string
q=phone
is appended to the URL to filter the products.
Creating Data
To create new data, you can use the http.Post
function or create a custom POST request with http.NewRequest
.
Example: Adding a New Product
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
// Define the product data
product := map[string]interface{}{
"title": "BMW Pencil",
// Add other product data as needed
}
jsonData, err := json.Marshal(product)
if err != nil {
log.Fatal(err)
}
// Create the POST request
response, err := http.Post("https://dummyjson.com/products/add", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var result map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
Explanation:
- Data is encoded to JSON using
json.Marshal
. http.Post
sends a POST request with the JSON data in the body.
Updating Data
To update existing data, you use an HTTP PUT or PATCH request. Go’s http.NewRequest
allows you to create these requests.
Example: Updating a Product
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
// Define the updated product data
updatedProduct := map[string]interface{}{
"title": "iPhone Galaxy +1",
}
jsonData, err := json.Marshal(updatedProduct)
if err != nil {
log.Fatal(err)
}
// Create the PUT request
req, err := http.NewRequest("PUT", "https://dummyjson.com/products/1", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var result map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
Explanation:
http.NewRequest
creates a PUT request to update the product.- The
Content-Type
header is set toapplication/json
.
Deleting Data
To delete data, you send an HTTP DELETE request using http.NewRequest
.
Example: Deleting a Product
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
// Create the DELETE request
req, err := http.NewRequest("DELETE", "https://dummyjson.com/products/1", nil)
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var result map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
Explanation:
http.NewRequest
creates a DELETE request.- The response body is decoded to handle any response data from the server.
Conclusion
Go’s net/http
package provides powerful tools for making HTTP requests, allowing you to fetch, create, update, and delete data from APIs. Whether you’re retrieving data with http.Get
, sending POST requests with http.Post
, or managing updates and deletions with custom requests, Go’s HTTP handling capabilities offer flexibility and control for interacting with web services.