

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: HTTP Methods - GET
incomplete
2: Why Use HTTP Methods?
incomplete
3: POST Requests
incomplete
4: Status Codes
incomplete
5: Status Code Property
incomplete
6: HTTP PUT
incomplete
7: Patch vs. PUT
incomplete
8: Delete
incomplete
This lesson's interactive features are locked, please to keep using them
An HTTP POST request sends data to a server, typically to create a new resource.
The body of the request is the payload sent to the server. The special Content-Type header is used to tell the server the format of the body: application/json for JSON data in our case. POST requests are generally not safe methods to call multiple times because that would create duplicate records. For example, you wouldn't want to accidentally send a tweet twice.
Like http.Get, the standard library's http.Post function can be used to send simple POST requests. The trouble is, it's a bit limited. And because we need to add an X-API-Key header, the simple http.Post function won't work for us. Instead, we need to use http.NewRequest:
type Comment struct {
Id string `json:"id"`
UserId string `json:"user_id"`
Comment string `json:"comment"`
}
func createComment(url, apiKey string, commentStruct Comment) (Comment, error) {
// encode our comment as json
jsonData, err := json.Marshal(commentStruct)
if err != nil {
return Comment{}, err
}
// create a new request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return Comment{}, err
}
// set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", apiKey)
// create a new client and make the request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return Comment{}, err
}
defer res.Body.Close()
// decode the json data from the response
// into a new Comment struct
var comment Comment
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&comment)
if err != nil {
return Comment{}, err
}
return comment, nil
}
Complete the createUser function. It should:
Don't copy paste from the code above. Type it out and understand what each line does.