in GraphQL, Can I send variables with Content-Type

2019-04-14 04:58发布

问题:

I've tried to use variables with graphql, but it seems impossible to send variables with 'application/graphql'.

Should i have to move on to Content-Type: 'application/json'?

回答1:

http://graphql.org/learn/serving-over-http/#post-request

A standard GraphQL POST request should use the application/json content type, and include a JSON-encoded body of the following form:

{
  "query": "...",
  "operationName": "...",
  "variables": { "myVariable": "someValue", ... }
}

operationName and variables are optional fields. operationName is only required if multiple operations are present in the query.

In addition to the above, we recommend supporting two additional cases:

... If the "application/graphql" Content-Type header is present, treat the HTTP POST body contents as the GraphQL query string.

In my understanding, Content-Type: "application/graphql" is Shorthand for Querying without variables.

So my answer is "Yes, If I want to use variables field, I have to use Content-Type: "application/json" header



回答2:

What prevents you from passing the variables in the query string and the query in the body?

POST /graphql?variables={"id":1234}
Content-Type: application/graphql
query ($id: ID!) {
    Post(id: $id) {
        id
        title
        body
    }
}


回答3:

According to Facebook's express-graphql HTTP Usage, variables can be passed as URL parameters. Here is an example:

/graphql?query=query+getUser($id:ID){user(id:$id){name}}&variables={"id":"4"}

For application/json, there is separate section for variables. For POST body with application/graphql and GET requests, URL query: variables={...} can be used.



标签: graphql