pigfox
pigfox

Reputation: 1399

GraphQL request json request body could not be decoded:

I am new to GraphQL so I looked at my Postman request. This is the raw Postman request.

Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Cache-Control: no-cache
Postman-Token: e3239924-6e8a-48b9-bc03-3216ea6da544
Host: localhost:4000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 94
Request Body
query: "query {
    getTodo(todoId:3) {
        id
        text
        done
    }
}"

I tried the following

var url = "http://localhost:4000/query"

func TestGetTodoByID(t *testing.T) {
    jsonData := `query {
    getTodo(todoId:3) {
        id
        text
        done
    }
}`

    fmt.Println(jsonData)

    request, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonData)))
    request.Header.Set("Content-Type", "application/json")
    request.Header.Set("Content-Length", fmt.Sprint(len(jsonData)))

    client := &http.Client{Timeout: time.Second * 10}
    response, err := client.Do(request)
    defer response.Body.Close()
    if err != nil {
        fmt.Printf("The HTTP request failed with error %s\n", err)
    }
    data, err := io.ReadAll(response.Body)
    if err != nil {
        fmt.Printf("Error reading response with error %s\n", err)
    }
    responseBody := string(data)
    if status := response.StatusCode; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }
    expected := `{
    "data": {
        "getTodo": {
            "id": 3,
            "text": "qwert333 hello",
            "done": true
        }
    }
}`
    if responseBody != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            responseBody, expected)
    }
}

Then I got the following error:

api_test.go:41: handler returned wrong status code: got 400 want 200
api_test.go:54: handler returned unexpected body: got {"errors":[{"message":"json request body could not be decoded: invalid character 'q' looking for beginning of value body:query {\n    getTodo(todoId:3) {\n        id\n        text\n        done\n    }\n}"}],"data":null} want {

Then I also tried exactly what I found in the Postman console

    jsonData := `"query":"query {
    getTodo(todoId:3) {
        id
        text
        done
    }
}"`

This gave me a slightly different error

api_test.go:41: handler returned wrong status code: got 400 want 200
api_test.go:54: handler returned unexpected body: got {"errors":[{"message":"json request body could not be decoded: json: cannot unmarshal string into Go value of type graphql.RawParams body:\"query\":\"query {\n    getTodo(todoId:3) {\n        id\n        text\n        done\n    }\n}\""}],"data":null} want {

Any ideas?

Upvotes: 1

Views: 1822

Answers (1)

David Maze
David Maze

Reputation: 159800

The standard GraphQL JSON format is actually a JSON object. In a Go context, the easiest way to create this is with a structure annotated for the encoding/json package. (You may go looking for a dedicated GraphQL client package that has this structure predefined.)

So for example you might create a structure for the minimal form of that structure

type GraphQLRequest struct{
        Query string `json:"query"`
        Variables map[string]interface{} `json:"variables,omitempty"`
}

and then create an instance of that structure and serialize it

query := `query GetTodo($id: ID!) {
  getTodo(todoId: $id) { id, name, done }
}`
request := GraphQLRequest{
        Query: query,
        Variables: map[string]interface{}{
                "id": 3,
        }
}
jsonData, err := json.Marshal(request)
if (err != nil) {
        panic(err) // or handle it however you would otherwise
}
request, err := http.NewRequest("POST", url, jsonData)
...

You may find it similarly useful to json.Unmarshal() the response data into a structure that has the standard format, with a Data field matching the shape of your query.

Upvotes: 1

Related Questions