in GraphQL, Can I send variables with Content-Type

2019-04-14 05:20发布

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'?

标签: graphql
3条回答
我想做一个坏孩纸
2楼-- · 2019-04-14 05:36

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-14 05:42

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
    }
}
查看更多
小情绪 Triste *
4楼-- · 2019-04-14 05:51

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.

查看更多
登录 后发表回答