@http
The @http directive enables GraphQL fields to be resolved using REST API endpoints, simplifying the integration of external data sources.
@http Directive Definition
directive @http(
url: String!
method: Method
query: [InputKeyValue!]
body: JSON
headers: [InputKeyValue!]
batchKey: [String!]
onRequest: String
onResponseBody: String
select: JSON
dedupe: Boolean
) on FIELD_DEFINITION
Example: Basic Usage of @http
type Query {
users: [User]
@http(url: "https://jsonplaceholder.typicode.com/users")
}
In this example, adding the @http directive to the users field of the Query type indicates reliance on a REST API for the users field. The url argument specifies the REST API's url, which is https://jsonplaceholder.typicode.com/users in this scenario. Querying the users field prompts the GraphQL server to issue a GET request to https://jsonplaceholder.typicode.com/users.
Directive Arguments
url
The url parameter defines the API endpoint. It can also contain dynamic segments with Mustache templates for variable substitution:
type Query {
user(id: ID!): User
@http(
url: "https://jsonplaceholder.typicode.com/users/{{.args.id}}"
)
}
method
Specifies the HTTP method for the request. Defaults to GET if not specified:
type Mutation {
createUser(input: UserInput!): User
@http(
method: "POST"
url: "https://jsonplaceholder.typicode.com/users"
)
}
query
Represents the API call's query parameters, either as a static object or with dynamic parameters using Mustache templates. These parameters append to the URL.
type Query {
userPosts(id: ID!): [Post]
@http(
url: "https://jsonplaceholder.typicode.com/posts"
query: [
{
key: "userId"
value: "{{.args.id}}"
skipEmpty: false
}
]
)
}
Query Fields:
- key : Represents the name of the query parameter.
- value : A string literal or a mustache template representing the value of query parameter.
- skipEmpty : When set to
truethe query parameter is skipped if the value of the parameter is null, defaults to false.
When batchKey is present, orkait considers the first query parameter to be the batch query key, so remember to adjust the order of the items accordingly.
body
Defines the API call's body, necessary for methods like POST or PUT. Pass it as a static object or use Mustache templates for variable substitution from the GraphQL variables.
type Mutation {
createUser(input: UserInput!): User
@http(
method: "POST"
url: "https://jsonplaceholder.typicode.com/users"
body: "{{.args.input}}"
)
}
In the example above, the createUser mutation sends a POST request to /users, with the input object converted to JSON and included in the request body.