graphqlswift/graphql-vapor
A Swift library for integrating [GraphQL](https://github.com/GraphQLSwift/GraphQL) with [Vapor](https://github.com/vapor/vapor), enabling you to easily expose GraphQL APIs in your Vapor applications.
Features
- Simple integration of GraphQL schemas with Vapor routing
- Compatibility with the GraphQL over HTTP spec
- Subscription support using WebSockets, with support for
graphql-transport-wsandgraphql-wssubprotocols - Built-in GraphiQL IDE
Installation
Add GraphQLVapor as a dependency in your Package.swift:
dependencies: [
.package(url: "https://github.com/NeedleInAJayStack/graphql-vapor.git", from: "1.0.0"),
]Then add it to your target:
.target(
name: "YourTarget",
dependencies: [
.product(name: "GraphQLVapor", package: "graphql-vapor"),
]
)Usage
To use this package, you must already have a GraphQL schema. You can use graphql-generator, Graphiti, or GraphQL to construct one.
See the HelloWorld project for a full working example.
Basic Example
import GraphQL
import GraphQLVapor
import Vapor
// Define your GraphQL schema
let schema = try GraphQLSchema(
query: GraphQLObjectType(
name: "Query",
fields: [
"hello": GraphQLField(
type: GraphQLString,
resolve: { _, _, _, _ in
"World"
}
)
]
)
)
// Define your Context
struct GraphQLContext: Sendable {}
// Register GraphQL to the Vapor Application
app.graphql(schema: schema) { _ in
return GraphQLContext()
}Now just run the application! You can view the GraphiQL IDE at /graphql, or query directly using GET or POST:
curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ hello }"}'Response:
{
"data": {
"hello": "World"
}
}See the RouteBuilder.graphql function documentation for advanced configuration options.
Computing GraphQL Context
The required closure in the graphql function is used to compute the GraphQLContext object, which is injected into each GraphQL resolver. The inputs argument passes in data from the request so that the Context can be created dynamically:
app.graphql(schema: schema) { inputs in
return GraphQLContext(
userID: inputs.vaporRequest.auth.userID,
logger: inputs.vaporRequest.logger,
debug: inputs.vaporRequest.headers[.init("debug")!] != nil,
operationName: inputs.graphQLRequest.operationName
)
}WebSockets
Subscription support via WebSockets is provided, and can be enabled by in the subscriptionProtocols configuration:
app.graphql(schema: schema, config: .init(subscriptionProtocols: [.websocket])) { _ in
GraphQLContext()
}graphql-ws and graphql-transport-ws subprotocols are supported.
Graphiti
If using Graphiti to build your GraphQL schema, you must provide an instance of the Resolver to the rootValue argument. For example:
let graphqlSchema: Graphiti.Schema<Resolver, Context> = try graphqlSchema()
app.graphql(
schema: graphqlSchema.schema,
rootValue: Resolver() // This must be included
) { _ in
Context()
}Package Metadata
Repository: graphqlswift/graphql-vapor
Default branch: main
README: README.md