Go

In Go, we'll be using the net/http standard library to send HTTP requests. Here's how you can use the book search API with Go:
First, make sure you import the necessary libraries at the top of your file:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
Then, you can use the following code to make the API request:
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
}
type Query struct {
Query string `json:"query"`
}
func searchBook(query string) ([]Book, error) {
url := "https://api.promptjoy.com/api/mVMCpq"
var jsonData = []byte(`{"query":"` + query + `"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", os.Getenv("PROMPTJOY_API_KEY"))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var books []Book
err = json.Unmarshal(body, &books)
if err != nil {
return nil, err
}
return books, nil
}
func main() {
books, err := searchBook("your_search_term")
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
} else {
for _, book := range books {
fmt.Println("Title: " + book.Title + ", Author: " + book.Author)
}
}
}
Replace "your_search_term" with the book you're searching for. This function will return a slice of books.
Remember to handle exceptions and errors as needed in your actual application code.
Note: In this example, the API key is retrieved from environment variables for security reasons. Ensure that you've set the PROMPTJOY_API_KEY environment variable in your environment where this code will be executed.
Last modified 8mo ago