Jon Nicholson
Jon Nicholson

Reputation: 1161

Constructing a JSON value to POST as part of HTTP request

I'm currently attempting to build a variable, convert it to JSON and use it to post to my database.

However, every time I try to post the data it's returning a 'JSON is not valid' error, indicating it's not constructed right.

I need to pass in two variables, which are initialised as part of the request by being passed in as query values.

Does anyone know why my JSON isn't valid?

Here's my code:

dataString := string(` { "credentials_id": "12345", "user_id": "12", "variable1": ` + variable1 + `, "variable2": ` + variable2 + ` }`)

    fmt.Println(dataString)

    req, err = http.NewRequest("POST", "https://api-call-url/bla", strings.NewReader(finalDataString))

    if err != nil {
        log.Print(err)
        fmt.Println("Error was not equal to nil at first stage.")
        os.Exit(1)
    }

    req.Header.Add("apikey", os.Getenv("APIKEY"))
    req.Header.Add("Authorization", "Bearer "+os.Getenv("APIKEY"))
    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Prefer", "return=representation")

    resp, err = client.Do(req)
    if err != nil {
        fmt.Println("Error posting data to database.")
        os.Exit(1)
    }

    respBody, _ = ioutil.ReadAll(resp.Body)

    w.WriteHeader(resp.StatusCode)
    w.Write(respBody)

Upvotes: 1

Views: 67

Answers (1)

Davide Madrisan
Davide Madrisan

Reputation: 2320

You should json.Marshal the payload data as shown in these examples.

So something like:

import (
        "bytes"
        "encoding/json"
        "net/http"
)

[...]

payload, _ := json.Marshal(map[string]string{
        "credentials_id": "12345",
        "user_id":        "12",
        "variable1":      variable1,
        "variable2":      variable2,
})

req, err = http.NewRequest("POST", "https://api-call-url/bla", bytes.NewReader(payload))

[...]

defer resp.Body.Close()

respBody, _ = ioutil.ReadAll(resp.Body)

var data interface{}
json.Unmarshal([]byte(respBody), &data)

You can find a complete example here.

Upvotes: 3

Related Questions