Search code examples
gogithub-api

Unexpected error response from GitHub API 422 when attempting to create issue


When posting an issue to GitHub API V3 I am getting an unexpected response. Namely 422 Unprocessable Entity. However the detail of the error is for the Search endpoint rather that the POST create endpoint. {"message":"Validation Failed","errors":[{"resource":"Search","field":"q","code":"missing"}],"documentation_url":"https://developer.github.com/v3/search"}

My instinct is that I have messed up the json but it is pretty simple and I can't see the issue. I have tried various solutions posted here and elsewhere but not found what I am doing wrong. This is a coding exercise rather than anything intended for production but driving me mildly insane.

  • Tested in Debug what the Request body is just before being posted. {"title":"Hello World","body":"dfsdfsdf\n"}
  • Tried removing the body as it is optional, same issue.
  • Tested in Debug that request is of type POST
  • Tested in Debug that authorization header is correct.
  • Removed authorization key and received 401 as expected.

The posting function:

func CreateIssue (issue *NewIssue) (*IssueDetailsResult, error){
issueJson, err := json.Marshal(issue)
if err != nil {
    log.Fatal(err)
    os.Exit(1)
}
req, err := http.NewRequest("POST", github.IssuesURL, bytes.NewBuffer(issueJson))
req.Header.Set("Authorization", "token "+os.Getenv("UPGITUSER"))
req.Header.Set( "Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
    os.Exit(1)
}
if resp.StatusCode != http.StatusCreated {
    bodyBytes, _ := ioutil.ReadAll(resp.Body)
    body := string(bodyBytes)
    resp.Body.Close()
    return nil, fmt.Errorf("create issue failed:%s", resp.Status + "\ntext: " + body)
}
var result IssueDetailsResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
    resp.Body.Close()
    return nil, err
}
resp.Body.Close()
return &result, nil

}

Would expect 201 from GitHubAPI.


Solution

  • The response is a strong indicator that the request is being sent to the wrong endpoint.

    You can use net/http/httputil's DumpRequestOut to inspect the requests you are about to send and to ensure that they are what you expect them to be.