I tried working with Apiary and made a universal template to send JSON to mock server and have this code:
package main import ( "encoding/json" "fmt" "github.com/jmcvetta/napping" "log" "net/http" ) func main() { url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>", url) s := napping.Session{} h := &http.Header{} h.Set("X-Custom-Header", "myvalue") s.Header = h var jsonStr = []byte(` { "title": "Buy cheese and bread for breakfast." }`) var data map[string]json.RawMessage err := json.Unmarshal(jsonStr, &data) if err != nil { fmt.Println(err) } resp, err := s.Post(url, &data, nil, nil) if err != nil { log.Fatal(err) } fmt.Println("response Status:", resp.Status()) fmt.Println("response Headers:", resp.HttpResponse().Header) fmt.Println("response Body:", resp.RawText()) }
This code doesn't send JSON properly, but I don't know why. The JSON string can be different in every call. I can't use Struct
for this.
To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.
POST requestsIn Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.
I'm not familiar with napping, but using Golang's net/http
package works fine (playground):
func main() { url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>", url) var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("response Status:", resp.Status) fmt.Println("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With