Skip to content

GraphQLSwift/graphql-vapor

Repository files navigation

GraphQLVapor

WARNING: This package is in v0.x beta. It's API is still evolving and is subject to breaking changes in minor version bumps.

A Swift library for integrating GraphQL with Vapor, enabling you to easily expose GraphQL APIs in your Vapor applications.

Features

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

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.

To build a type-safe GraphQL schema, consider graphql-generator or Graphiti