GraphQL LogoGraphQL

代码

使用 GraphQL

因为 GraphQL 是一种通信模式,所以有很多工具可以帮助您开始使用它,这些工具支持各种语言的 GraphQL。

语言支持

排序方式

JavaScript

服务器

GraphQL.js

最新版本6 个月前
星标20k
许可证MIT 许可证

GraphQL 规范的参考实现,旨在用于在 Node.js 环境中运行 GraphQL。

要从命令行运行 GraphQL.js hello world 脚本

npm install graphql

然后运行 node hello.js,其中 hello.js 中包含以下代码

var { graphql, buildSchema } = require("graphql")
var schema = buildSchema(`
type Query {
hello: String
}
`)
var rootValue = { hello: () => "Hello world!" }
var source = "{ hello }"
graphql({ schema, source, rootValue }).then(response => {
console.log(response)
})

graphql-yoga

最新版本1 周前
星标8k
许可证MIT 许可证

GraphQL Yoga 是一个功能齐全的跨平台 GraphQL over HTTP 规范兼容的 GraphQL 服务器,使用 Envelop 和 GraphQL Tools。

  • 基于 Fetch API RequestResponse 对象构建
  • 符合 GraphQL over HTTP 规范
  • 由 Envelop 提供支持的可扩展 GraphQL 引擎
  • 通过 HTTP 的 GraphQL 订阅
  • 使用 GraphQL 处理文件上传
  • 与 AWS Lambda、Cloudflare Workers、Deno、Express、Next.js、SvelteKit 等集成。

要运行一个使用 graphql-yoga 的 hello world 服务器

npm install graphql-yoga graphql

然后使用 createServer 导入创建一个服务器

import { createServer } from "http"
import { createSchema, createYoga } from "graphql-yoga"
createServer(
createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => "Hello Hello Hello",
},
},
}),
})
).listen(4000, () => {
console.info("GraphQL Yoga is listening on https://127.0.0.1:4000/graphql")
})

根据您的部署目标,您可能需要使用额外的库。有关更多详细信息,请参阅 文档

Mercurius

最新版本1 天前
星标2k
许可证MIT 许可证

Mercurius 是一个灵活且可扩展的 GraphQL 适配器,适用于 Fastify,这是一个速度极快的 Web 框架,具有最少的开销和强大的插件架构。

要运行一个使用 mercurius 的 hello world 脚本

npm install fastify mercurius

然后运行node app.js,代码在app.js

const Fastify = require("fastify")
const mercurius = require("mercurius")
const schema = `
type Query {
hello(name: String): String!
}
`
const resolvers = {
Query: {
hello: async (_, { name }) => `hello ${name || "world"}`,
},
}
const app = Fastify()
app.register(mercurius, {
schema,
resolvers,
})
app.listen(3000)
// Call IT!
// curl 'https://127.0.0.1:3000/graphql' \
// -H 'content-type: application/json' \
// --data-raw '{"query":"{ hello(name:\"Marcurius\") }" }'

GraphQL-WS

最新版本1 个月前
星标2k
许可证MIT 许可证

一致、零依赖、延迟、简单、符合 GraphQL over WebSocket 协议的服务器和客户端。

Apollo Server

最新版本2 周前
Star 数14k
许可证MIT 许可证

来自 Apollo 的 GraphQL 服务器,适用于任何 Node.js HTTP 框架

要使用 Apollo Server 运行一个 hello world 服务器

npm install @apollo/server graphql

然后运行node server.js,代码在server.js

import { ApolloServer } from "@apollo/server"
import { startStandaloneServer } from "@apollo/server/standalone"
const server = new ApolloServer({
typeDefs,
resolvers,
})
const { url } = await startStandaloneServer(server)
console.log(`🚀 Server ready at ${url}`)

Apollo Server 内置了独立的 HTTP 服务器和 Express 中间件,并拥有一个框架集成 API,通过社区集成支持所有Node.js HTTP 服务器框架和无服务器环境

Apollo Server 拥有一个插件 API,与 Apollo Studio 集成,以及性能和安全功能,例如缓存自动持久化查询CSRF 防御

GraphQL-SSE

最新版本3 个月前
Star 数362
许可证MIT 许可证

零依赖、HTTP/1 安全、简单、符合 GraphQL over Server-Sent Events 协议的服务器和客户端。

GraphQL-HTTP

最新版本6 个月前
Star 数272
许可证MIT 许可证

简单、可插拔、零依赖、符合 GraphQL over HTTP 规范的服务器、客户端和审计套件。

GraphQLBox 服务器

Stars23
许可证MIT 许可证

一个可扩展的 GraphQL 服务器,包含用于缓存、请求解析、调试、订阅等的模块。

以下示例安装并初始化 GraphQLBox 服务器,并启用持久化缓存和调试。

npm install @graphql-box/core @graphql-box/server @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/execute @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/redis @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"
import redis from "@cachemap/redis"
import reaper from "@cachemap/reaper"
import CacheManager from "@graphql-box/cache-manager"
import Client from "@graphql-box/client"
import DebugManager from "@graphql-box/debug-manager"
import Execute from "@graphql-box/execute"
import RequestParser from "@graphql-box/request-parser"
import Server from "@graphql-box/server"
import { makeExecutableSchema } from "@graphql-tools/schema"
import { performance } from "perf_hooks"
import { schemaResolvers, schemaTypeDefs } from "./schema"
import logger from "./logger"
const schema = makeExecutableSchema({
typeDefs: schemaTypeDefs,
resolvers: schemaResolvers,
})
const server = new Server({
client: new Client({
cacheManager: new CacheManager({
cache: new Cachemap({
name: "server-cache",
reaper: reaper({ interval: 300000 }),
store: redis(/* configure */),
}),
cascadeCacheControl: true,
typeCacheDirectives: {
// Add any type specific cache control directives in the format:
// TypeName: "public, max-age=3",
},
}),
debugManager: new DebugManager({
environment: "server",
log: (...args) => {
logger.log(...args)
},
name: "SERVER",
performance,
}),
requestManager: new Execute({ schema }),
requestParser: new RequestParser({ schema }),
}),
})
// Meanwhile... somewhere else in your code
app.use("api/graphql", graphqlServer.request())

客户端

Apollo Client

最新版本1 天前
Stars19k
许可证MIT 许可证

一个强大的 JavaScript GraphQL 客户端,旨在与 React、React Native、Angular 2 或纯 JavaScript 很好地配合使用。

urql

最新版本1 周前
星标8k
许可证MIT 许可证

一个高度可定制且通用的 GraphQL 客户端,您可以随着项目的增长添加诸如规范化缓存之类的功能。

urql 是一个 GraphQL 客户端,它为多个框架提供了一组帮助程序。它旨在高度可定制且通用,因此您可以从开始第一个 GraphQL 项目一直到构建复杂的应用程序并尝试 GraphQL 客户端。

  • 目前支持 React、React Native、Preact、Svelte 和 Vue,并受 GraphQL Code Generator 支持。
  • 逻辑且简单的默认行为和文档缓存,以及通过 @urql/exchange-graphcache 进行的规范化缓存
  • 通过“交换”(附加包)完全可定制的行为

Relay

最新版本1 个月前
Stars18k
许可证MIT 许可证

Facebook 用于构建与 GraphQL 后端通信的 React 应用程序的框架。

Relay 是一个 JavaScript 框架,用于构建数据驱动的 React 应用程序。

  • 声明式:再也不用使用命令式 API 与您的数据存储进行通信。只需使用 GraphQL 声明您的数据需求,让 Relay 找出如何以及何时获取您的数据。
  • 共置:查询与依赖它们的视图并存,因此您可以轻松地推断您的应用程序。Relay 将查询聚合到高效的网络请求中,以仅获取您需要的内容。
  • 变异:Relay 允许您使用 GraphQL 变异在客户端和服务器上更改数据,并提供自动数据一致性、乐观更新和错误处理。

了解如何在自己的项目中使用 Relay.

GraphQL 请求

最新版本3 年前
星标6k
许可证MIT 许可证

一个简单且灵活的 JavaScript GraphQL 客户端,可在所有 JavaScript 环境(浏览器、Node.js 和 React Native)中使用 - 本质上是 fetch 的轻量级包装器。

AWS Amplify

最新版本19 小时前
星标9k
许可证Apache 许可证 2.0

一个用于使用云服务进行应用程序开发的 JavaScript 库,它支持 GraphQL 后端和用于处理 GraphQL 数据的 React 组件。

graphqurl

星标3k
许可证Apache 许可证 2.0

带有自动完成、订阅和 GraphiQL 的 GraphQL 的 curl。也是一个非常简单的通用 JavaScript GraphQL 客户端。

GraphQL-WS

最新版本1 个月前
星标2k
许可证MIT 许可证

一致、零依赖、延迟、简单、符合 GraphQL over WebSocket 协议的服务器和客户端。

graphql-hooks

最新版本2 个月前
星标2k
许可证其他

具有微小捆绑包、SSR 支持和缓存的最小 React hooks-first GraphQL 客户端

  • 🥇 一流的 hooks API
  • ⚖️ 微小捆绑包:仅 7.6kB(2.8 压缩)
  • 📄 全面 SSR 支持:请参阅 graphql-hooks-ssr
  • 🔌 插件缓存:请参阅 graphql-hooks-memcache
  • 🔥 不再有 render props 地狱
  • ⏳ 轻松处理加载和错误状态

快速入门#

npm install graphql-hooks

首先,您需要创建一个客户端并使用提供程序包装您的应用程序

import { GraphQLClient, ClientContext } from "graphql-hooks"
const client = new GraphQLClient({
url: "/graphql",
})
function App() {
return (
<ClientContext.Provider value={client}>
{/* children */}
</ClientContext.Provider>
)
}

现在,在您的子组件中,您可以使用 useQuery

import { useQuery } from "graphql-hooks"
const HOMEPAGE_QUERY = `query HomePage($limit: Int) {
users(limit: $limit) {
id
name
}
}`
function MyComponent() {
const { loading, error, data } = useQuery(HOMEPAGE_QUERY, {
variables: {
limit: 10,
},
})
if (loading) return "Loading..."
if (error) return "Something Bad Happened"
return (
<ul>
{data.users.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
)
}

Lokka

星标2k
许可证MIT 许可证

一个简单且灵活的 JavaScript GraphQL 客户端,可在所有 JavaScript 环境(浏览器、Node.js 和 React Native)中使用。

nanogql

星标422
许可证MIT 许可证

使用模板字符串的小巧 GraphQL 客户端库。

GraphQL-SSE

最新版本3 个月前
Star 数362
许可证MIT 许可证

零依赖、HTTP/1 安全、简单、符合 GraphQL over Server-Sent Events 协议的服务器和客户端。

GraphQL-HTTP

最新版本6 个月前
Star 数272
许可证MIT 许可证

简单、可插拔、零依赖、符合 GraphQL over HTTP 规范的服务器、客户端和审计套件。

graphql-ts-client

最新版本3 个月前
星标142
许可证MIT 许可证

用于 TypeScript 的 GraphQL 客户端,根据强类型查询请求自动推断返回数据的类型。

GraphQLBox 客户端

Stars23
许可证MIT 许可证

一个可扩展的 GraphQL 客户端,包含用于 React、缓存、请求解析、Web Workers、WebSockets 等的模块。

以下示例安装并初始化 GraphQLBox 客户端,并启用持久化缓存和调试功能。

npm install @graphql-box/core @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/fetch-manager @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/indexed-db @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"
import indexedDB from "@cachemap/indexed-db"
import reaper from "@cachemap/reaper"
import CacheManager from "@graphql-box/cache-manager"
import Client from "@graphql-box/client"
import DebugManager from "@graphql-box/debug-manager"
import FetchManager from "@graphql-box/fetch-manager"
import RequestParser from "@graphql-box/request-parser"
import introspection from "./introspection-query"
const requestManager = new FetchManager({
apiUrl: "/api/graphql",
batchRequests: true,
logUrl: "/log/graphql",
})
const client = new Client({
cacheManager: new CacheManager({
cache: new Cachemap({
name: "client-cache",
reaper: reaper({ interval: 300000 }),
store: indexedDB(/* configure */),
}),
cascadeCacheControl: true,
typeCacheDirectives: {
// Add any type specific cache control directives in the format:
// TypeName: "public, max-age=3",
},
}),
debugManager: new DebugManager({
environment: "client",
log: (message, data, logLevel) => {
requestManager.log(message, data, logLevel)
},
name: "CLIENT",
performance: self.performance,
}),
requestManager,
requestParser: new RequestParser({ introspection }),
})
// Meanwhile... somewhere else in your code
const { data, errors } = await client.request(queryOrMutation)

Grafoo

最新版本5 年前
星标274
许可证MIT 许可证

一个多功能的 GraphQL 客户端,仅需 1.6kb 即可与多个框架的视图层集成。

gq-loader

星标59
许可证未知

一个简单的 JavaScript GraphQL 客户端,通过 webpack 加载器将 *.gql 文件用作模块。

工具

SpectaQL

星标1k
许可证MIT 许可证

SpectaQL 从 GraphQL 架构生成静态 HTML 文档。

SpectaQL 是一个 Node.js 库,使用各种选项为 GraphQL 架构生成静态文档。

  • 从使用内省查询的实时端点。
  • 从包含内省查询结果的文件。
  • 从文件、文件或 glob 指向 SDL 中的架构定义。

开箱即用,SpectaQL 生成一个单一的 3 列 HTML 页面,并允许您在几个内置主题之间进行选择。该项目的首要目标是易于定制和高度可定制——它是可主题化的,几乎所有内容都可以被覆盖或定制。

npm install --dev spectaql
# OR
yarn add -D spectaql
# Then generate your docs
npm run spectaql my-config.yml
# OR
yarn spectaql my-config.yml

Postgraphile

最新版本5 个月前
星标12k
许可证其他

在几秒钟内从 PostgreSQL 架构构建一个强大、可扩展且高效的 GraphQL API;为您节省数周甚至数月的开发时间。

GraphQL 代码生成器

最新发布3 周前
Star11k
许可证MIT 许可证

GraphQL 代码生成器,支持灵活的自定义插件和模板,例如 Typescript(前端和后端)、React Hooks、解析器签名等。

GraphQL 工具

最新版本1 天前
Star5k
许可证MIT 许可证

一套用于更快开发 GraphQL 工具的实用程序(Schema 和文档加载、Schema 合并等)。

GraphiQL

最新版本2 周前
Star16k
许可证MIT 许可证

一个交互式的浏览器内 GraphQL IDE。

GraphQLShield

最新发布1 年前
Star4k
许可证MIT 许可证

一个 GraphQL 工具,用于简化权限层的创建。

GraphQL Shield 帮助您为您的应用程序创建权限层。使用直观的规则 API,您将在每个请求中获得盾牌引擎的力量,并通过智能缓存减少每个请求的加载时间。这样,您可以确保您的应用程序保持快速,并且不会暴露任何内部数据。

import { rule, shield, and, or, not } from "graphql-shield"
// Rules
const isAuthenticated = rule({ cache: "contextual" })(
async (parent, args, ctx, info) => {
return ctx.user !== null
}
)
const isAdmin = rule({ cache: "contextual" })(
async (parent, args, ctx, info) => {
return ctx.user.role === "admin"
}
)
const isEditor = rule({ cache: "contextual" })(
async (parent, args, ctx, info) => {
return ctx.user.role === "editor"
}
)
// Permissions
const permissions = shield({
Query: {
frontPage: not(isAuthenticated),
fruits: and(isAuthenticated, or(isAdmin, isEditor)),
customers: and(isAuthenticated, isAdmin),
},
Mutation: {
addFruitToBasket: isAuthenticated,
},
Fruit: isAuthenticated,
Customer: isAdmin,
})
// Server
const server = new GraphQLServer({
typeDefs,
resolvers,
middlewares: [permissions],
context: req => ({
...req,
user: getUser(req),
}),
})

GraphQL 标量

最新发布2 天前
星标2k
许可证MIT 许可证

一个自定义 GraphQL 标量类型的库,用于创建精确的、类型安全的 GraphQL 模式。

GraphQL 模块

最新发布4 个月前
星标1k
许可证MIT 许可证

GraphQL 模块允许您将后端实现分离成小型、可重用、易于实现和易于测试的片段。

GraphQL 中间件

最近发布8 个月前
星标1k
许可证MIT 许可证

将您的 GraphQL 解析器拆分为中间件函数。

GraphQL 中间件是一个模式包装器,允许您有效地管理多个解析器之间的附加功能。

功能#

💡 易于使用:直观且熟悉的 API,您可以在一秒钟内上手。💪 强大:允许完全控制您的解析器(之前、之后)。🌈 兼容:适用于任何 GraphQL 模式。

示例#

const { ApolloServer } = require("apollo-server")
const { makeExecutableSchema } = require("@graphql-tools/schema")
const typeDefs = `
type Query {
hello(name: String): String
bye(name: String): String
}
`
const resolvers = {
Query: {
hello: (root, args, context, info) => {
console.log(`3. resolver: hello`)
return `Hello ${args.name ? args.name : "world"}!`
},
bye: (root, args, context, info) => {
console.log(`3. resolver: bye`)
return `Bye ${args.name ? args.name : "world"}!`
},
},
}
const logInput = async (resolve, root, args, context, info) => {
console.log(`1. logInput: ${JSON.stringify(args)}`)
const result = await resolve(root, args, context, info)
console.log(`5. logInput`)
return result
}
const logResult = async (resolve, root, args, context, info) => {
console.log(`2. logResult`)
const result = await resolve(root, args, context, info)
console.log(`4. logResult: ${JSON.stringify(result)}`)
return result
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
const schemaWithMiddleware = applyMiddleware(schema, logInput, logResult)
const server = new ApolloServer({
schema: schemaWithMiddleware,
})
await server.listen({ port: 8008 })

GraphQL Mesh

最近发布3 分钟前
星标3k
许可证MIT 许可证

GraphQL Mesh 允许您使用 GraphQL 查询语言访问不运行 GraphQL 的远程 API(以及运行 GraphQL 的 API)中的数据。它可以用作其他服务的网关,或作为从远程 API 聚合数据的本地 GraphQL 模式运行。

SOFA

最新版本2 个月前
星标1k
许可证MIT 许可证

从您的 GraphQL API 生成 REST API。

GraphQL 实时查询

最新发布1 年前
星标431
许可证MIT 许可证

任何 GraphQL 模式或传输的 GraphQL 实时。

用于为 IDE(诊断、自动完成等)构建 GraphQL 语言服务的接口。

GraphQL 检查器

最新版本3 个月前
星标2k
许可证MIT 许可证

比较模式、验证文档、查找重大更改、查找类似类型、模式覆盖率等等。

GraphQL 配置

最新版本5 个月前
星标1k
许可证MIT 许可证

一个配置适用于所有 GraphQL 工具(大多数工具、编辑器和 IDE 支持)。

GraphQL-ESLint

最新版本6 个月前
星标1k
许可证MIT 许可证

GraphQL-ESLint 将 GraphQL AST 集成到 ESLint 核心(作为解析器)。

GraphQL-HTTP

最新版本6 个月前
Star 数272
许可证MIT 许可证

简单、可插拔、零依赖、符合 GraphQL over HTTP 规范的服务器、客户端和审计套件。

Microfiber

Stars30
许可证MIT 许可证

一个用于查询和操作 GraphQL Introspection Query 结果的库。

Microfiber 是一个 JavaScript 库,它允许

  • 在您的 Introspection Query 结果中查找特定查询、变异、类型、字段、参数或订阅。
  • 从您的 Introspection Query 结果中删除特定查询、变异、类型、字段/输入字段、参数或订阅。
  • 删除引用不存在于 - 或已从 - 您的 Introspection Query 结果中删除的类型的查询、变异、字段/输入字段或参数。
npm install microfiber
# OR
yarn add microfiber

然后在 JS 中

import { Microfiber } from 'microfiber'
const introspectionQueryResults = {...}
const microfiber = new Microfiber(introspectionQueryResults)
// ...do some things to your schema with `microfiber`
const cleanedIntrospectonQueryResults = microfiber.getResponse()

GraphQL CLI

最新版本3 年前
星标2k
许可证MIT 许可证

一个用于常见 GraphQL 开发工作流程的命令行工具。

GiraphQL

最新版本2 周前
星标2k
LicenseISC License

一个基于插件的模式构建器,用于在 typescript 中创建代码优先的 GraphQL 模式。

GiraphQL 使编写类型安全的模式变得简单,并且无需代码生成器、构建过程或广泛的手动类型定义。

import { ApolloServer } from "apollo-server"
import SchemaBuilder from "@giraphql/core"
const builder = new SchemaBuilder({})
builder.queryType({
fields: t => ({
hello: t.string({
args: {
name: t.arg.string({}),
},
resolve: (parent, { name }) => `hello, ${name || "World"}`,
}),
}),
})
new ApolloServer({
schema: builder.toSchema({}),
}).listen(3000)

Brangr

Last Release9 months ago
Stars1
LicenseMozilla Public License 2.0

浏览任何图 - 任何 GraphQL 服务的用户友好查看器

Brangr - Browse Any Graph

  • Brangr 是一款简单、独特的工具,任何 Web 服务器都可以托管它,为任何 GraphQL 服务(或多个服务)提供用户友好的浏览器/查看器。

  • Brangr 通过一系列用户可配置的布局,以吸引人的方式格式化 GraphQL 结果。它允许用户提取生成的 HTML 及其源 JSON。它提供了一个智能的模式浏览器。它内置了文档。

  • Brangr 使托管它的网站能够向用户展示一系列预制 GraphQL 请求,用户可以根据需要编辑这些请求,并允许他们创建自己的请求。它还允许网站为格式化结果的所有方面定义自定义 CSS 样式。

  • 公共 Brangr 网站 上试用它。

示例

query {
heroes(_layout:{type:table}) { # _layout arg not sent to service
first
last
}
}

Brangr 将上述查询呈现如下(尽管不在引用块中)

heroes...
First Last
ArthurDent
Ford Prefect
ZaphodBeeblebrox

服务器

graphql-go

最新版本11 个月前
Star 数10k
许可证MIT 许可证

Go / Golang 的 GraphQL 实现。

99designs/gqlgen

最新版本1 周前
Star 数10k
许可证MIT 许可证

基于 Go generate 的 GraphQL 服务器库。

graph-gophers/graphql-go

最新发布1 年前
Star5k
许可证BSD 2-Clause "Simplified" License

专注于易用性的 GraphQL 服务器。

samsarahq/thunder

星标2k
许可证MIT 许可证

一个 GraphQL 实现,具有简单的模式构建、实时查询和批处理功能。

graphql-go-tools

最新版本5 个月前
星标1k
许可证MIT 许可证

一个用于在 Go 中构建 GraphQL 服务器、网关、代理服务器和中间件的工具集合。

graphql-go-tools 实现构建 GraphQL 服务器、网关和代理服务器的所有基本模块。从词法分析、解析、验证、规范化,一直到查询规划和执行。

它也可以被理解为一个 GraphQL 编译器,能够添加自己的后端。只需实现几个接口,你就可以教编译器如何与任何后端进行 GraphQL 通信。

以下后端已经实现:GraphQL,支持 Apollo Federation / Supergraph。 数据库:PostgreSQL、MySQL、SQLite、CockroachDB、MongoDB、SQLServer、OpenAPI / RESTKafka

要了解如何实现新的后端,请查看 静态数据源,因为它是最简单的。

它已在许多企业中使用多年,经过实战检验,并得到积极维护。

graphql-relay-go

星标422
许可证MIT 许可证

一个 Go/Golang 库,用于帮助构建支持 react-relay 的 graphql-go 服务器。

appointy/jaal

最新版本3 年前
Star76
许可证MIT 许可证

使用 Go 开发符合规范的 GraphQL 服务器。

EGGQL

Star32
许可证MIT 许可证

易于使用,完整的 Go 实现 GraphQL。简单且无模式。

Eggql 的目的是使创建 GraphQL 服务器尽可能简单。您无需创建 GraphQL 模式(尽管您可以查看创建的模式,如果您有兴趣)。它目前处于测试版发布,但除了订阅之外,它是 GraphQL 服务器的完整实现。

需要明确的是,它支持所有这些 GraphQL 功能:参数(包括默认值)、对象/列表/枚举/输入/接口/联合类型、别名、片段、变量、指令、变异、内联片段、描述、内省和自定义标量。

测试(jMeter)表明,对于简单的查询,它与其他 Go 实现一样快或更快。我们正在努力改进性能,包括缓存、数据加载器、复杂度限制等。

要运行 eggql hello world 服务器,只需构建并运行此 Go 程序

package main
import "github.com/andrewwphillips/eggql"
func main() {
http.Handle("/graphql", eggql.New(struct{ Message string }{Message: "hello, world"}))
http.ListenAndServe(":80", nil)
}

这将创建一个具有单个 message 字段的根 Query 对象。要测试它,请使用 curl 发送查询

$ curl -XPOST -d '{"query": "{ message }"}' localhost:80/graphql

您将获得此响应

{
"data": {
"message": "hello, world"
}
}

客户端

genqlient

最新版本2 周前
星标1k
许可证MIT 许可证

一个真正类型安全的 Go GraphQL 客户端。

genqlient 是一个 Go 库,用于轻松生成类型安全的代码来查询 GraphQL API。它利用了 GraphQL 和 Go 都是类型化语言的事实,以确保在编译时您的代码正在发出有效的 GraphQL 查询并正确使用结果,所有这些都只需最少的样板代码。

genqlient 提供

  • 编译时验证 GraphQL 查询:永远不要再发送无效的 GraphQL 查询!
  • 类型安全的响应对象:genqlient 为每个查询生成正确的类型,因此您知道响应将正确反序列化,并且永远不需要使用 interface{}
  • 生产就绪:genqlient 在可汗学院的生产环境中使用,为全球数百万名学习者和教师提供支持。

machinebox/graphql

最新版本5 年前
星标1k
许可证Apache 许可证 2.0

一个优雅的低级 GraphQL HTTP 客户端。

graphql

星标1k
许可证MIT 许可证

一个 Go 语言实现的 GraphQL 客户端。

go-graphql-client

最新版本2 周前
Stars366
许可证MIT 许可证

一个支持 Mutation、Query 和 Subscription 的 GraphQL Go 客户端。

工具

graphjin

最新版本3 个月前
星标3k
许可证Apache 许可证 2.0

一个即时的 GraphQL 到 SQL 编译器。可以用作独立服务或 Go 库。以前称为 super-graph。

PHP

服务器

API Platform

最新版本1 周前
星标8k
许可证MIT 许可证

API Platform 是一个功能齐全、灵活且可扩展的 API 框架,构建在 Symfony 之上。

以下类足以创建一个兼容 Relay 的 GraphQL 服务器和一个支持现代 REST 格式(JSON-LD、JSONAPI 等)的超媒体 API。

<?php
namespace AppEntity;
use ApiPlatformCoreAnnotationApiResource;
use DoctrineORMMapping as ORM;
/**
* Greet someone!
*
* @ApiResource
* @ORMEntity
*/
class Greeting
{
/**
* @ORMId
* @ORMColumn(type="guid")
*/
public $id;
/**
* @var string Your nice message
*
* @ORMColumn
*/
public $hello;
}

API Platform 的其他功能包括数据验证、身份验证、授权、弃用、缓存和 GraphiQL 集成。

graphql-php

最新版本1 周前
Star5k
许可证MIT 许可证

GraphQL 参考实现的 PHP 移植版。

WPGraphQL

Last Release5 days ago
Star4k
LicenseGNU General Public License v3.0

一个免费的开源 WordPress 插件,为任何 WordPress 网站提供可扩展的 GraphQL 架构和 API。

Lighthouse

最新版本1 周前
星标3k
许可证MIT 许可证

一个用于 Laravel 的 GraphQL 服务器。

Siler

最新版本3 年前
星标1k
许可证MIT 许可证

Siler 是一个 PHP 库,使用高级抽象来处理 GraphQL。

运行 Siler hello world 脚本

type Query {
hello: String
}
<?php
declare(strict_types=1);
require_once '/path/to/vendor/autoload.php';
use SilerDiactoros;
use SilerGraphql;
use SilerHttp;
$typeDefs = file_get_contents(__DIR__.'/schema.graphql');
$resolvers = [
'Query' => [
'hello' => 'world',
],
];
$schema = Graphqlschema($typeDefs, $resolvers);
echo "Server running at http://127.0.0.1:8080";
Httpserver(Graphqlpsr7($schema), function (Throwable $err) {
var_dump($err);
return Diactorosjson([
'error' => true,
'message' => $err->getMessage(),
]);
})()->run();

它还提供基于 Apollo 工作方式构建 WebSocket 订阅服务器的功能。

GraphQLBundle

最新版本1 周前
星标1k
许可证MIT 许可证

一个用于 Symfony 的 GraphQL 服务器。

GraphQLite

最新发布12 小时前
星标1k
许可证MIT 许可证

GraphQLite 是一个提供基于注解的 GraphQL 模式定义语法的库。

它与框架无关,并提供适用于 Symfony 和 Laravel 的绑定。此代码声明了一个“product”查询和一个“Product”类型。

class ProductController
{
/**
* @Query()
*/
public function product(string $id): Product
{
// Some code that looks for a product and returns it.
}
}
/**
* @Type()
*/
class Product
{
/**
* @Field()
*/
public function getName(): string
{
return $this->name;
}
// ...
}

其他 GraphQLite 功能包括验证、安全、错误处理、通过数据加载器模式加载...

Railt

最新版本5 年前
星标360
许可证MIT 许可证

一个 PHP GraphQL 框架。

Gato GraphQL

最新发布6 天前
星标348
许可证GNU 通用公共许可证 v2.0

与 WordPress 中的所有数据交互

graphql-relay-php

最新发布2 年前
星标271
许可证BSD 3 条款“新”或“修订”许可证

一个帮助构建支持 react-relay 的 graphql-php 服务器的库。

GraPHPinator

最新发布4 个月前
星标39
许可证MIT 许可证

一个用于现代 PHP 的 GraphQL 实现。包括最新草案中的功能、中间件指令和具有额外功能的模块。

GraPHPinator 是 GraphQL 服务器的完整功能 PHP 实现。它的工作是将查询字符串转换为给定模式的已解析 Json 结果。

  • 旨在符合 GraphQL 规范的最新草案。
  • 完全类型安全,因此最低所需的 PHP 版本为 8.0。为了获得极大的清晰度和安全性,牺牲了一点便利性 - 没有随机配置arrays,没有混合类型,没有可变函数参数 - 此库不会试图从冗长中拯救你,但确保你始终知道你得到了什么。
  • 代码优先。
  • 灵活。易于使用模块或中间件指令扩展额外功能。
  • 包括一些超出官方规范范围的可选扩展
    • 打印机 - 用于 GraPHPinator 类型系统的模式打印。
    • 额外类型 - 一些有用且常用的类型,包括标量类型和复合类型。
    • 约束指令 - 类型系统指令,用于在 GraphQL 类型系统之上声明额外的验证。
    • Where 指令 - 可执行指令,用于过滤列表中的值。
    • 使用 multipart-formdata 规范进行文件上传(目前已捆绑)。
    • 查询成本限制模块 - 模块通过限制最大深度或节点数量来限制查询成本。
  • 项目由多个较小的包组成,这些包可以独立使用。

serge

Stars5
LicenseGNU General Public License v3.0

使用 GraphQL 定义您的 CQRS/ES 领域模型,并让 serge 生成代码来处理 GraphQL 请求。

Java / Kotlin

服务器

graphql-java

最新版本1 天前
星标6k
许可证MIT 许可证

一个用于构建 GraphQL API 的 Java 库。

请参阅 GraphQL Java 网站上的 入门教程

使用 graphql-java 执行 hello world GraphQL 查询的代码

import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;
public class HelloWorld {
public static void main(String[] args) {
String schema = "type Query{hello: String}";
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
RuntimeWiring runtimeWiring = newRuntimeWiring()
.type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
ExecutionResult executionResult = build.execute("{hello}");
System.out.println(executionResult.getData().toString());
// Prints: {hello=world}
}
}

有关更多信息,请参阅 graphql-java 文档

领域图服务 (DGS) 框架

最新版本1 天前
星标3k
许可证Apache 许可证 2.0

DGS 框架(领域图服务)是 Netflix 开发的用于 Spring Boot 的 GraphQL 服务器框架。

DGS 框架(领域图服务)是 Netflix 开发的用于 Spring Boot 的 GraphQL 服务器框架。

功能包括

  • 基于注解的 Spring Boot 编程模型
  • 用于将查询测试编写为单元测试的测试框架
  • Gradle 代码生成插件,用于从模式创建类型
  • 轻松集成 GraphQL Federation
  • 与 Spring Security 集成
  • GraphQL 订阅(WebSockets 和 SSE)
  • 文件上传
  • 错误处理
  • 许多扩展点

有关如何开始,请参阅 DGS 框架入门

graphql-kotlin

最新版本1 个月前
星标2k
许可证Apache 许可证 2.0

一组用于在 Kotlin 中运行 GraphQL 客户端和服务器的库。

GraphQL Kotlin 采用代码优先方法来生成 GraphQL 模式。鉴于 Kotlin 和 GraphQL 之间的相似性,例如定义可空/不可空类型的能力,可以从 Kotlin 代码生成模式,而无需任何单独的模式规范。要创建反应式 GraphQL Web 服务器,请将以下依赖项添加到您的 Gradle 构建文件中

// build.gradle.kts
implementation("com.expediagroup", "graphql-kotlin-spring-server", latestVersion)

我们还需要提供一个支持包列表,这些包可以通过反射扫描以公开您的模式对象。将以下配置添加到您的 application.yml 文件中

graphql:
packages:
- "com.your.package"

有了上述配置,我们现在可以创建我们的模式。为了在 GraphQL 模式中公开您的查询、变异和/或订阅,您只需实现相应的标记接口,它们将被 graphql-kotlin-spring-server 自动配置库自动拾取。

@Component
class HelloWorldQuery : Query {
fun helloWorld() = "Hello World!!!"
}

这将导致一个具有以下模式的反应式 GraphQL Web 应用程序

type Query {
helloWorld: String!
}

有关更多详细信息,请参阅 graphql-kotlin 文档

GraphQL Spring Boot

最新版本3 个月前
星标2k
许可证MIT 许可证

来自 GraphQL Java Kickstart 的 GraphQL Spring Boot

GraphQL Spring Boot 将任何 Spring Boot 应用程序变成 GraphQL 服务器

启动包括以下功能:

有关如何开始,请参阅 GraphQL Java Kickstart 入门

Spring for GraphQL

最新版本4 周前
星标1k
许可证Apache 许可证 2.0

Spring for GraphQL 为基于 GraphQL Java 构建的 Spring 应用程序提供支持。

Spring for GraphQL 为基于 GraphQL Java 构建的 Spring 应用程序提供支持。请参阅官方 Spring 指南,了解如何在 15 分钟内构建 GraphQL 服务。

  • 它是 GraphQL Java 团队和 Spring 工程团队的共同合作成果。
  • 我们的共同理念是尽可能少地提供意见,同时专注于对各种用例的全面支持。
  • 它旨在成为所有 Spring、GraphQL 应用程序的基础。

功能

  • 服务器处理通过 HTTP、WebSocket 和 RSocket 的 GraphQL 请求。
  • 基于注解的编程模型,其中 @Controller 组件使用注解来声明处理程序方法,这些方法具有灵活的方法签名,用于获取特定 GraphQL 字段的数据。例如
@Controller
public class GreetingController {
@QueryMapping
public String hello() {
return "Hello, world!";
}
}
  • 客户端支持通过 HTTP、WebSocket 和 RSocket 执行 GraphQL 请求。
  • 专门支持测试通过 HTTP、WebSocket 和 RSocket 的 GraphQL 请求,以及直接针对服务器进行测试。

要开始使用,请查看 https://start.spring.io 上的 Spring GraphQL 启动器以及此存储库中的 示例

Jimmer

最新版本1 周前
星标1k
许可证Apache 许可证 2.0

一个革命性的 ORM 框架,适用于 Java 和 Kotlin,它还为快速开发基于 Spring GraphQL 的应用程序提供专门的 API。

介绍#

  1. SpringBoot 自 2.7 版本起引入了 Spring GraphQL。Jimmer 为快速开发基于 Spring GraphQL 的应用程序提供专门的 API。

  2. 支持两种 API:Java API 和 Kotlin API。

  3. 强大且对 GraphQL 友好的缓存支持。

  4. 比其他流行的 ORM 解决方案更快,请参阅基准测试:https://babyfish-ct.github.io/jimmer/docs/benchmark/

  5. 比其他流行的 ORM 解决方案更强大。

    在 ORM 设计中应考虑三个方面

    a. 查询。b. 更新。c. 缓存。

    每个方面都针对具有任意深度的对象树,而不是简单对象。这种独特的设计带来了其他流行解决方案无法比拟的便利性。

链接#

KGraphQL

最新发布1 年前
星标292
许可证MIT 许可证

KGraphQL 是 GraphQL 的 Kotlin 实现。它提供了一个丰富的 DSL 来设置 GraphQL 架构。

以下是如何基于 Kotlin 数据类创建简单架构的示例,以及应用于类的属性解析器。

data class Article(val id: Int, val text: String)
fun main() {
val schema = KGraphQL.schema {
query("article") {
resolver { id: Int?, text: String ->
Article(id ?: -1, text)
}
}
type<Article> {
property<String>("fullText") {
resolver { article: Article ->
"${article.id}: ${article.text}"
}
}
}
}
schema.execute("""
{
article(id: 5, text: "Hello World") {
id
fullText
}
}
""").let(::println)
}

KGraphQL 在幕后使用协程来提供出色的异步性能。

有关更深入的用法,请参阅 KGraphQL 文档

Ktor 插件#

KGraphQL 具有一个 Ktor 插件,它为您提供了一个功能齐全的 GraphQL 服务器,只需一个 install 函数调用。以下示例展示了如何在 Ktor 中设置 GraphQL 服务器,它将通过输入 localhost:8080/graphql 为您提供一个 GraphQL Playground

fun Application.module() {
install(GraphQL) {
playground = true
schema {
query("hello") {
resolver { -> "World!" }
}
}
}
}

您可以按照 Ktor 教程 从头开始设置一个带有 Ktor 的 KGraphQL 服务器。

graphql-calculator

最新发布2 年前
星标103
许可证Apache 许可证 2.0

一个轻量级的 graphql 计算引擎。

GraphQL Calculator 是一个轻量级的 graphql 计算引擎,用于更改 graphql 查询的执行行为。

以下是一些关于如何在 graphql 查询中使用 GraphQL Calculator 的示例。

query basicMapValue($userIds: [Int]) {
userInfoList(userIds: $userIds) {
id
age
firstName
lastName
fullName: stringHolder @map(mapper: "firstName + lastName")
}
}
query filterUserByAge($userId: [Int]) {
userInfoList(userIds: $userId) @filter(predicate: "age>=18") {
userId
age
firstName
lastName
}
}
query parseFetchedValueToAnotherFieldArgumentMap($itemIds: [Int]) {
itemList(itemIds: $itemIds) {
# save sellerId as List<Long> with unique name "sellerIdList"
sellerId @fetchSource(name: "sellerIdList")
name
saleAmount
salePrice
}
userInfoList(userIds: 1)
# transform the argument of "userInfoList" named "userIds" according to expression "sellerIdList" and expression argument,
# which mean replace userIds value by source named "sellerIdList"
@argumentTransform(
argumentName: "userIds"
operateType: MAP
expression: "sellerIdList"
dependencySources: ["sellerIdList"]
) {
userId
name
age
}
}

有关更多信息,请参阅 graphql-calculator 自述文件

MicroProfile GraphQL

最新发布2 年前
星标95
许可证Apache 许可证 2.0

MP GraphQL 是用于构建 GraphQL 应用程序的代码优先规范。它使用类似于 JAX-RS 的注释和设计模式来实现快速开发。

MicroProfile GraphQL 是用于构建 GraphQL 应用程序的 GraphQL 服务器和客户端规范。它独特的基于注释的 API 方法可以实现快速应用程序开发。使用 MP GraphQL API 编写的应用程序是可移植的,可以部署到 Java 服务器运行时,例如 Open LibertyQuarkusHelidonWildfly。这意味着您的应用程序可以使用其他 JakartaMicroProfile 技术。

MP GraphQL 功能包括

  • 基于注解的 API
  • 与 Jakarta CDI 集成
  • 类型安全且动态的客户端 API
  • 异常处理
  • 轻松集成 Jakarta 和 MicroProfile 技术

想要开始?查看这些资源

或这些视频

客户端

Apollo Kotlin

最新版本58 分钟前
Star4k
许可证MIT 许可证

一个强类型、缓存的 GraphQL 客户端,适用于 JVM、Android 和 Kotlin 多平台。

Apollo Kotlin(以前称为 Apollo Android)是一个 GraphQL 客户端,支持 Android、Java8+、iOS 和 Kotlin 多平台。它具有以下功能

  • Java 和 Kotlin 多平台代码生成
  • 查询、变异和订阅
  • 无反射解析
  • 规范化缓存
  • 自定义标量类型
  • HTTP 缓存
  • 自动持久化查询
  • 查询批处理
  • 文件上传
  • Espresso IdlingResource
  • 用于测试的假模型
  • AppSync 和 graphql-ws websockets
  • GraphQL AST 解析器

graphql-kotlin

最新版本1 个月前
星标2k
许可证Apache 许可证 2.0

一组用于在 Kotlin 中运行 GraphQL 客户端和服务器的库。

GraphQL Kotlin 提供了一组轻量级类型安全的 GraphQL HTTP 客户端。该库提供了 Ktor HTTP 客户端和 Spring WebClient 基于参考实现,以及允许使用其他引擎的自定义实现。Jackson 和 kotlinx-serialization 类型安全数据模型在构建时由提供的 Gradle 和 Maven 插件生成。

要生成将与 GraphQL Kotlin Spring WebClient 一起使用的 Jackson 模型,请将以下内容添加到您的 Gradle 构建文件中

// build.gradle.kts
import com.expediagroup.graphql.plugin.gradle.graphql
plugins {
id("com.expediagroup.graphql") version $latestGraphQLKotlinVersion
}
dependencies {
implementation("com.expediagroup:graphql-kotlin-spring-client:$latestGraphQLKotlinVersion")
}
graphql {
client {
// target GraphQL endpoint
endpoint = "https://127.0.0.1:8080/graphql"
// package for generated client code
packageName = "com.example.generated"
}
}

默认情况下,GraphQL Kotlin 插件将在 src/main/resources 下查找查询文件。给定 HelloWorldQuery.graphql 示例查询

query HelloWorldQuery {
helloWorld
}

插件将生成实现 GraphQLClientRequest 接口的简单 POJO 类,并表示 GraphQL 请求。

package com.example.generated
import com.expediagroup.graphql.client.types.GraphQLClientRequest
import kotlin.String
import kotlin.reflect.KClass
const val HELLO_WORLD_QUERY: String = "query HelloWorldQuery {\n helloWorld\n}"
class HelloWorldQuery: GraphQLClientRequest<HelloWorldQuery.Result> {
override val query: String = HELLO_WORLD_QUERY
override val operationName: String = "HelloWorldQuery"
override fun responseType(): KClass<HelloWorldQuery.Result> = HelloWorldQuery.Result::class
data class Result(
val helloWorld: String
}
}

然后,我们可以使用目标客户端执行查询。

package com.example.client
import com.expediagroup.graphql.client.spring.GraphQLWebClient
import com.expediagroup.graphql.generated.HelloWorldQuery
import kotlinx.coroutines.runBlocking
fun main() {
val client = GraphQLWebClient(url = "https://127.0.0.1:8080/graphql")
runBlocking {
val helloWorldQuery = HelloWorldQuery()
val result = client.execute(helloWorldQuery)
println("hello world query result: ${result.data?.helloWorld}")
}
}

有关更多详细信息,请参阅 graphql-kotlin 客户端文档

节点

最新发布4年前
星标305
许可证Apache 许可证 2.0

一个为从标准模型定义构建查询而设计的 GraphQL JVM 客户端。由美国运通提供。

工具

GraphQL Java 生成器

星标50
许可证MIT 许可证

GraphQL Java 生成器是一个工具,用于生成 Java 代码以加快 GraphQL API 的客户端和服务器开发。

  • GraphQL Java 客户端:它生成调用 GraphQL 端点的 Java 类,以及包含服务器返回数据的 POJO。然后可以通过调用简单的 Java 方法(见下面的示例)来查询 GraphQL 端点。
  • GraphQL Java 服务器:它基于 graphql-java(上面列出)。它生成所有样板代码。您只需要实现特定于服务器的内容,即 GraphQL 类型之间的连接。GraphQL Java 生成器可作为 Maven 插件 使用。Gradle 插件即将推出。请注意,GraphQL Java 生成器是一个加速器:生成的代码不依赖于任何特定于 GraphQL Java 生成器的库。因此,它可以帮助您开始构建基于 graphql-java 的应用程序。代码生成后,您可以像任何标准 Java 应用程序一样手动编辑它,并摆脱 GraphQL Java 生成器。当然,您可以(也应该,在我们看来:),在您的项目发展时继续使用 GraphQL Java 生成器。

C# / .NET

服务器

graphql-dotnet

最新版本1 个月前
星标6k
许可证MIT 许可证

.NET 的 GraphQL

using System;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson; // First add PackageReference to GraphQL.SystemTextJson
public class Program
{
public static async Task Main(string[] args)
{
var schema = Schema.For(@"
type Query {
hello: String
}
");
var json = await schema.ExecuteAsync(_ =>
{
_.Query = "{ hello }";
_.Root = new { Hello = "Hello World!" };
});
Console.WriteLine(json);
}
}

Hot Chocolate

最新发布3小时前
Star5k
许可证MIT 许可证

Hot Chocolate 是一个面向 .NET 的开源 GraphQL 服务器。

Hot Chocolate 消除了构建完整 GraphQL 服务器的复杂性,让您专注于交付下一个重大突破。

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
WebHost
.CreateDefaultBuilder(args)
.ConfigureServices(services =>
services
.AddGraphQLServer()
.AddQueryType<Query>())
.Configure(builder =>
builder
.UseRouting()
.UseEndpoints(e => e.MapGraphQL()))
.Build()
.Run();
public class Query
{
public Hero GetHero() => new Hero();
}
public class Hero
{
public string Name => "Luke Skywalker";
}

graphql-net

星标1k
许可证MIT 许可证

将 GraphQL 转换为 IQueryable

Entity GraphQL

最新版本1 天前
星标373
许可证MIT 许可证

一个用于 .NET Core 的 GraphQL 库。轻松地将您的数据模型公开为 GraphQL API,或将多个数据源整合到单个 GraphQL 架构中。

// expose an exisiting data model with ASP.NET & EF Core
public class Startup {
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DemoContext>();
// Auto build a schema from DemoContext. Alternatively you can build one from scratch
services.AddGraphQLSchema<DemoContext>(options =>
{
// modify the schema (add/remove fields or types), add other services
});
}
public void Configure(IApplicationBuilder app, DemoContext db)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// defaults to /graphql endpoint
endpoints.MapGraphQL<DemoContext>();
});
}
}

一套用于在 .NET 中实现高性能 GraphQL 服务器的软件包。忠实地实现了官方 2018 规范。具有批处理执行支持(又名数据加载器);支持自定义标量;基于 ASP.NET Core 的 HTTP 服务器;解析查询缓存;模块化 API 构建(等效于架构拼接);完全的内省支持;运行时指标和配额。

客户端

Strawberry Shake

最新发布3小时前
Star5k
许可证MIT 许可证

Strawberry Shake 是一个面向 .NET 的开源反应式 GraphQL 客户端。

Strawberry Shake 消除了状态管理的复杂性,并允许您通过 GraphQL 与本地和远程数据进行交互。

您可以使用 Strawberry Shake 来

  • 从您的 GraphQL 查询生成 C# 客户端。
  • 通过 GraphQL 与本地和远程数据进行交互。
  • 使用反应式 API 与您的状态进行交互。
client.GetHero
.Watch(ExecutionStrategy.CacheFirst)
.Subscribe(result =>
{
Console.WriteLine(result.Data.Name);
})

GraphQL.Client

最新版本5 小时前
星标1k
许可证MIT 许可证

一个用于 .NET 的 GraphQL 客户端。

ZeroQL

最新版本4 周前
星标236
许可证MIT 许可证

ZeroQL 是一个面向 C# 的开源 GraphQL 客户端。

ZeroQL 是一个高性能的 C# 友好 GraphQL 客户端。它支持类似 Linq 的语法,并且不需要 Reflection.Emit 或表达式。因此,在运行时提供了与原始 HTTP 调用非常接近的性能。

您可以使用 ZeroQL 来

  • 从 GraphQL 架构生成 C# 客户端。
  • 从您的 C# 代码生成和执行 graphql 查询。
  • 不需要手动编写 GraphQL。
  • 支持 .Net Core、.Net Framework、Xamarin、Unity 应用程序。
var userId = 10;
var response = await qlClient.Query(q => q
.User(userId, o => new
{
o.Id,
o.FirstName,
o.LastName
}));

graphql-net-client

星标94
许可证MIT 许可证

用于 .NET 的基本示例 GraphQL 客户端。

SAHB.GraphQLClient

最新版本3 年前
星标43
许可证MIT 许可证

GraphQL 客户端,支持从 C# 类生成查询。

服务器

Graphene

最新版本7 个月前
星标8k
许可证MIT 许可证

一个用于构建 GraphQL API 的 Python 库。

运行 Graphene 的 hello world 脚本

pip install graphene

然后运行 python hello.py,代码在 hello.py

import graphene
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="World"))
def resolve_hello(self, info, name):
return 'Hello ' + name
schema = graphene.Schema(query=Query)
result = schema.execute('{ hello }')
print(result.data['hello']) # "Hello World"

还有一些针对 Relay、Django、SQLAlchemy 和 Google App Engine 的绑定。

Strawberry

最新版本1 周前
Star4k
许可证MIT 许可证

Strawberry 是一个 Python 库,用于使用现代 Python 特性(如类型提示)实现代码优先的 GraphQL 服务器。

以下是一个 Strawberry hello world 的示例,首先安装库

pip install strawberry-graphql

创建一个包含以下内容的 app.py 文件

import strawberry
@strawberry.type
class Query:
@strawberry.field
def hello(self, name: str = "World") -> str:
return f"Hello {name}"
schema = strawberry.Schema(query=Query)

然后运行 strawberry server app,您将拥有一个在 https://127.0.0.1:8000/ 上运行的基本模式服务器。

Strawberry 还提供 ASGI、Flask 和 Django 的视图,并提供数据加载器和跟踪等实用程序。

Ariadne

最新发布2 天前
星标2k
许可证BSD 3 条款“新”或“修订”许可证

Ariadne 是一个 Python 库,用于使用模式优先方法实现 GraphQL 服务器。它支持同步和异步查询执行,包含用于解决常见 GraphQL 服务器问题的电池,例如查询成本验证或性能跟踪,并且具有易于扩展或替换的简单 API。

Ariadne 可以使用 pip 安装

$ pip install ariadne

最小的“Hello world”服务器示例

from ariadne import ObjectType, gql, make_executable_schema
from ariadne.asgi import GraphQL
type_defs = gql(
"""
type Query {
hello: String!
}
"""
)
query_type = ObjectType("Query")
@query_type.field("hello")
def resolve_hello(*_):
return "Hello world!"
schema = make_executable_schema(type_defs, query_type)
app = GraphQL(schema, debug=True)

使用 uvicorn 运行服务器

$ pip install uvicorn
$ uvicorn example:app

Tartiflette

最新发布2 年前
星标1k
许可证MIT 许可证

一个 Python 3.6+ (asyncio) 库,用于构建 GraphQL API。

运行 tartiflette hello world 脚本

pip install tartiflette

然后运行 python hello.py,代码在 hello.py

import asyncio
from tartiflette import Engine, Resolver
@Resolver("Query.hello")
async def resolver_hello(parent, args, ctx, info):
return "hello " + args["name"]
async def run():
tftt_engine = Engine("""
type Query {
hello(name: String): String
}
""")
result = await tftt_engine.execute(
query='query { hello(name: "Chuck") }'
)
print(result)
# {'data': {'hello': 'hello Chuck'}}
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(run())

还有一个不错的 HTTP 包装器

Django Graphbox

最新版本2 个月前
Stars9
许可证MIT 许可证

用于为 Django 模型轻松构建具有基本 CRUD 操作的 GraphQL API 的包。

Django Graphbox 的快速入门

  1. 安装包
pip install django-graphbox
  1. 创建一个新的 Django 项目
django-admin startproject myproject
  1. 创建一个新的 Django 应用程序
cd myproject
python manage.py startapp myapp
  1. myapp/models.py 中定义您的 Django 模型
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
  1. 创建并运行迁移
python manage.py makemigrations
python manage.py migrate
  1. myapp/schema.py 中配置和构建您的 GraphQL 模式
from django_graphbox.builder import SchemaBuilder
from myapp.models import MyModel
builder = SchemaBuilder()
builder.add_model(MyModel)
query_class = builder.build_schema_query()
mutation_class = builder.build_schema_mutation()
  1. myproject/schema.py 中创建一个主模式(您可以在此主模式中添加自己的查询和变异)
import graphene
from myapp.schema import query_class, mutation_class
class Query(query_class, graphene.ObjectType):
pass
class Mutation(mutation_class, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query, mutation=Mutation)
  1. 将 GraphQL 视图添加到您的 myproject/urls.py
from django.urls import path
from graphene_file_upload.django import FileUploadGraphQLView
from django.views.decorators.csrf import csrf_exempt
from myproject.schema import schema
urlpatterns = [
path('graphql/', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True, schema=schema))),
]
  1. 运行服务器
python manage.py runserver
  1. https://127.0.0.1:8000/graphql/ 打开 GraphiQL 接口,开始查询您的 API!

您可以在 github 或 pypi 上找到包含身份验证、过滤器、验证等高级示例。

客户端

GQL

最新版本1 个月前
星标1k
许可证MIT 许可证

一个 Python 的 GraphQL 客户端。

sgqlc

Stars491
LicenseISC License

一个简单的 Python GraphQL 客户端。支持为在 GraphQL 架构中定义的类型生成代码。

Ariadne Codegen

最新版本2 周前
Stars193
许可证BSD 3 条款“新”或“修订”许可证

从任何架构和查询生成完全类型化的 Python GraphQL 客户端。

安装 Ariadne Codegen

$ pip install ariadne-codegen

创建 queries.graphql 文件

mutation CreateToken($username: String!, $password: String!) {
createToken(username: $username, password: $password) {
token
errors {
field
message
}
}
}

在您的 pyproject.toml 中添加 [ariadne-codegen] 部分

[ariadne-codegen]
queries_path = "queries.graphql"
remote_schema_url = "http://example.com/graphql/"

生成客户端

$ ariadne-codegen

并在您的 Python 项目中使用它

from graphql_client import Client
with Client("http://example.com/graphql/") as client:
result = client.create_token(username="Admin", password="Example123)
if result.errors:
error = result.errors[0]
raise ValidationError({error.field: error.message})
auth_token = result.token

python-graphql-client

Stars155
许可证MIT 许可证

适用于 Python 2.7+ 的简单 GraphQL 客户端。

Qlient

最新发布1 年前
Stars45
许可证MIT 许可证

一个快速且现代的 graphql 客户端,设计理念是简洁。

以下是一个 qlient hello world 的示例。

首先安装库

pip install qlient

创建一个包含以下内容的 swapi_client_example.py 文件

from qlient.http import HTTPClient, GraphQLResponse
client = HTTPClient("https://swapi-graphql.netlify.app/.netlify/functions/index")
res: GraphQLResponse = client.query.film(
# swapi graphql input fields
id="ZmlsbXM6MQ==",
# qlient specific
_fields=["id", "title", "episodeID"]
)
print(res.request.query) # query film($id: ID) { film(id: $id) { id title episodeID } }
print(res.request.variables) # {'id': 'ZmlsbXM6MQ=='}
print(res.data) # {'film': {'id': 'ZmlsbXM6MQ==', 'title': 'A New Hope', 'episodeID': 4}}

关闭文件并使用 python 运行它

python swapi_client_example.py

graphql-query

最新版本4 周前
Stars45
许可证MIT 许可证

为 python 生成完整的 GraphQL 查询字符串。

graphql_query 是 python 的完整 GraphQL 查询字符串构建器。使用 graphql_query,您可以 graphql_query 的文档可以在 https://denisart.github.io/graphql-query/ 找到。

$ pip install graphql_query

简单查询的代码

{
hero {
name
}
}

它是

from graphql_query import Operation, Query
hero = Query(name="hero", fields=["name"])
operation = Operation(type="query", queries=[hero])
print(operation.render())
"""
query {
hero {
name
}
}
"""

用于生成以下查询

query Hero($episode: Episode, $withFriends: Boolean!) {
hero(episode: $episode) {
name
friends @include(if: $withFriends) {
name
}
}
}

我们有

from graphql_query import Argument, Directive, Field, Operation, Query, Variable
episode = Variable(name="episode", type="Episode")
withFriends = Variable(name="withFriends", type="Boolean!")
arg_episode = Argument(name="episode", value=episode)
arg_if = Argument(name="if", value=withFriends)
hero = Query(
name="hero",
arguments=[arg_episode],
fields=[
"name",
Field(
name="friends",
fields=["name"],
directives=[Directive(name="include", arguments=[arg_if])]
)
]
)
operation = Operation(
type="query",
name="Hero",
variables=[episode, withFriends],
queries=[hero]
)
print(operation.render())
"""
query Hero(
$episode: Episode
$withFriends: Boolean!
) {
hero(
episode: $episode
) {
name
friends @include(
if: $withFriends
) {
name
}
}
}
"""

服务器

graphql-rust/juniper

最新发布1 小时前
星标6k
许可证其他

Rust 的 GraphQL 服务器库

Async-graphql

最新发布1 年前
星标3k
许可证Apache 许可证 2.0

Async-graphql 是一个高性能的服务器端库,支持所有 GraphQL 规范。

use async_graphql::*;
struct Query;
#[Object]
impl Query {
/// Returns the sum of a and b
async fn add(&self, a: i32, b: i32) -> i32 {
a + b
}
}

客户端

cynic

最新版本1 个月前
星标333
LicenseMozilla Public License 2.0

Rust 的自备类型 GraphQL 客户端

一个 Rust 客户端库,它从您提供的类型生成查询,并验证类型是否与您的模式形状匹配。

它提供了一个 生成器,用于从现有的 GraphQL 查询中引导类型。

使用示例

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
schema_path = "../schemas/starwars.schema.graphql",
query_module = "query_dsl",
graphql_type = "Root",
argument_struct = "FilmArguments"
)]
struct FilmDirectorQuery {
#[arguments(id = &args.id)]
film: Option<Film>,
}
#[derive(cynic::QueryFragment, Debug)]
#[cynic(
schema_path = "../schemas/starwars.schema.graphql",
query_module = "query_dsl",
graphql_type = "Film"
)]
struct Film {
title: Option<String>,
director: Option<String>,
}
#[derive(cynic::FragmentArguments)]
struct FilmArguments {
id: Option<cynic::Id>,
}
fn main() {
use cynic::{QueryBuilder, http::ReqwestBlockingExt};
let query = FilmDirectorQuery::build(&FilmArguments {
id: Some("ZmlsbXM6MQ==".into()),
})
reqwest::blocking::Client::new()
.post("https://swapi-graphql.netlify.com/.netlify/functions/index")
.run_graphql(query)
.unwrap()
}
mod query_dsl {
cynic::query_dsl!("../schemas/starwars.schema.graphql");
}

gql_client

星标47
许可证MIT 许可证

Rust 的最小 GraphQL 客户端

使用示例

use gql_client::Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let endpoint = "https://graphqlzero.almansi.me/api";
let query = r#"
query AllPostsQuery {
posts {
data {
id
}
}
}
"#;
let client = Client::new(endpoint);
let data: AllPosts = client.query::<AllPosts>(query).await.unwrap();
println!("{:?}" data);
Ok(())
}

Ruby

服务器

graphql-ruby

最新版本3 年前
Star5k
许可证MIT 许可证

一个用于构建 GraphQL API 的 Ruby 库。

要使用 graphql-ruby 运行一个 hello world 脚本

gem install graphql

然后使用 hello.rb 中的代码运行 ruby hello.rb

require 'graphql'
class QueryType < GraphQL::Schema::Object
field :hello, String
def hello
"Hello world!"
end
end
class Schema < GraphQL::Schema
query QueryType
end
puts Schema.execute('{ hello }').to_json

它还为 Relay 和 Rails 提供了不错的绑定。

Agoo

gemagoo
星标1k
许可证MIT 许可证

一个高性能的 Web 服务器,支持 GraphQL。Agoo 致力于为 GraphQL 提供一个简单易用的 API。

require 'agoo'
class Query
def hello
'hello'
end
end
class Schema
attr_reader :query
def initialize
@query = Query.new()
end
end
Agoo::Server.init(6464, 'root', thread_count: 1, graphql: '/graphql')
Agoo::Server.start()
Agoo::GraphQL.schema(Schema.new) {
Agoo::GraphQL.load(%^type Query { hello: String }^)
}
sleep
# To run this GraphQL example type the following then go to a browser and enter
# a URL of localhost:6464/graphql?query={hello}
#
# ruby hello.rb

Rails GraphQL

最新版本1 个月前
星标165
许可证MIT 许可证

一个面向 Rails 应用程序的新 GraphQL 服务器,专注于自然和 Ruby 风格的 DSL

require 'rails-graphql'
class GraphQL::AppSchema < GraphQL::Schema
query_fields do
field(:hello).resolve { 'Hello World!' }
end
end
puts GraphQL::AppSchema.execute('{ hello }')

少即是多!请查看 文档

Swift / Objective-C

服务器

Graphiti

最新发布4 个月前
星标1k
许可证MIT 许可证

Swift 库,用于快速、安全、轻松地构建 GraphQL 模式/类型。

GraphZahl

最新发布2 年前
星标143
许可证MIT 许可证

Swift 库,用于编写声明式、类型安全的 GraphQL API,无需任何样板代码。

客户端

Apollo iOS

最新版本1 周前
Star4k
许可证MIT 许可证

一个适用于 iOS 的 GraphQL 客户端,它将结果返回为特定于查询的 Swift 类型,并与 Xcode 集成,以并排显示您的 Swift 源代码和 GraphQL,并提供内联验证错误。

SwiftGraphQL

最新版本2 个月前
星标1k
许可证MIT 许可证

一个 GraphQL 客户端,让您忘记 GraphQL。

SwiftGraphQL 是一个 Swift 代码生成器和轻量级 GraphQL 客户端。它允许您使用 Swift 创建查询,并保证您创建的每个查询都是有效的。

该库围绕三个核心原则构建

🚀 如果您的项目编译成功,您的查询就能正常工作。 🦉 尽可能使用 Swift 代替 GraphQL。 🌳 您的应用程序模型应该独立于您的模式。

以下是 SwiftGraphQL 代码的简短预览

import SwiftGraphQL
// Define a Swift model.
struct Human: Identifiable {
let id: String
let name: String
let homePlanet: String?
}
// Create a selection.
let human = Selection.Human {
Human(
id: try $0.id(),
name: try $0.name(),
homePlanet: try $0.homePlanet()
)
}
// Construct a query.
let query = Selection.Query {
try $0.humans(human.list)
}
// Perform the query.
send(query, to: "http://swift-graphql.heroku.com") { result in
if let data = try? result.get() {
print(data) // [Human]
}
}

Graphaello

最新发布2 年前
Stars494
许可证MIT 许可证

一个使用 GraphQL 和 Apollo 在 SwiftUI 中编写声明式、类型安全和数据驱动应用程序的工具

GraphQL iOS

Stars62
许可证MIT 许可证

一个适用于 iOS 的 Objective-C GraphQL 客户端。

GraphQLite iOS

最新版本5 个月前
Stars5
许可证MIT 许可证

GraphQLite iOS SDK 是一个工具包,可以轻松地与 GraphQL 服务器进行交互。它还提供了一些其他功能,使 iOS 应用程序开发更加轻松。

服务器

absinthe

最新发布2 年前
Star4k
许可证其他

适用于 Elixir 的 GraphQL 实现。

Facebook GraphQL 的 Elixir 实现。

客户端

common_graphql_client

最新版本3 年前
星标43
许可证MIT 许可证

支持 HTTP 和 WebSocket 的 Elixir GraphQL 客户端

适用于 Elixir 的 GraphQL 客户端

服务器

Sangria

最新版本1 个月前
星标2k
许可证Apache 许可证 2.0

一个支持Relay 的 Scala GraphQL 库。

使用 sangria 的 hello world GraphQL 模式和查询示例

import sangria.schema._
import sangria.execution._
import sangria.macros._
val QueryType = ObjectType("Query", fields[Unit, Unit](
Field("hello", StringType, resolve = _ ⇒ "Hello world!")
))
val schema = Schema(QueryType)
val query = graphql"{ hello }"
Executor.execute(schema, query) map println

Caliban

最新版本2 周前
星标1k
许可证Apache 许可证 2.0

Caliban 是一个用于在 Scala 中构建 GraphQL 服务器和客户端的功能库。它提供最少的样板代码和出色的互操作性。

使用 caliban 的简单 GraphQL 模式和查询示例

import caliban._
import caliban.schema.Schema.auto._
// schema
case class Query(hello: String)
// resolver
val resolver = RootResolver(Query("Hello world!"))
val api = graphQL(resolver)
for {
interpreter <- api.interpreter
result <- interpreter.execute("{ hello }")
} yield result

客户端

Caliban

最新版本2 周前
星标1k
许可证Apache 许可证 2.0

Caliban 是一个用于在 Scala 中构建 GraphQL 服务器和客户端的功能库。它提供客户端代码生成和类型安全的查询。

使用 caliban 定义 GraphQL 查询并运行它的示例

// define your query using Scala
val query: SelectionBuilder[RootQuery, List[CharacterView]] =
Query.characters {
(Character.name ~ Character.nicknames ~ Character.origin)
.mapN(CharacterView)
}
import sttp.client3._
// run the query and get the result already parsed into a case class
val result = query.toRequest(uri"http://someUrl").send(HttpClientSyncBackend()).body

Flutter

客户端

graphql

最新版本2 个月前
星标3k
许可证MIT 许可证

Flutter 中的 GraphQL 客户端实现。

Ferry

星标1k
许可证MIT 许可证

Ferry 是一个简单、强大的 Flutter 和 Dart GraphQL 客户端。

服务器

lacinia

星标2k
许可证其他

GraphQL 规范的完整实现,旨在保持与规范的外部一致性。

graphql-clj

星标282
许可证Eclipse Public License 1.0

一个提供 GraphQL 实现的 Clojure 库。

使用 graphql-clj 执行 hello world GraphQL 查询的代码

(def schema "type QueryRoot {
hello: String
}")
(defn resolver-fn [type-name field-name]
(get-in {"QueryRoot" {"hello" (fn [context parent & rest]
"Hello world!")}}
[type-name field-name]))
(require '[graphql-clj.executor :as executor])
(executor/execute nil schema resolver-fn "{ hello }")

alumbra

最新版本6 年前
星标148
许可证MIT 许可证

一组可重用的 Clojure GraphQL 组件,符合alumbra.spec 中给出的数据结构。

(require '[alumbra.core :as alumbra]
'[claro.data :as data])
(def schema
"type Person { name: String!, friends: [Person!]! }
type QueryRoot { person(id: ID!): Person, me: Person! }
schema { query: QueryRoot }")
(defrecord Person [id]
data/Resolvable
(resolve! [_ _]
{:name (str "Person #" id)
:friends (map ->Person (range (inc id) (+ id 3)))}))
(def QueryRoot
{:person (map->Person {})
:me (map->Person {:id 0})})
(def app
(alumbra/handler
{:schema schema
:query QueryRoot}))
(defonce my-graphql-server
(aleph.http/start-server #'app {:port 3000}))
$ curl -XPOST "http://0:3000" -H'Content-Type: application/json' -d'{
"query": "{ me { name, friends { name } } }"
}'
{"data":{"me":{"name":"Person #0","friends":[{"name":"Person #1"},{"name":"Person #2"}]}}}

客户端

regraph

最新发布1 年前
星标455
许可证未知

一个在 Clojurescript 中实现的 GraphQL 客户端,支持 websockets。

服务器

Morpheus GraphQL

最近发布10 个月前
星标400
许可证MIT 许可证

一个用于构建 GraphQL API 的 Haskell 库。

使用 morpheus-graphql 的 Hello world 示例

# schema.gql
"""
A supernatural being considered divine and sacred
"""
type Deity {
name: String!
power: String @deprecated(reason: "no more supported")
}
type Query {
deity(name: String! = "Morpheus"): Deity!
}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module API (api) where
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.Morpheus (interpreter)
import Data.Morpheus.Document (importGQLDocument)
import Data.Morpheus.Types (RootResolver (..), Undefined (..))
import Data.Text (Text)
importGQLDocument "schema.gql"
rootResolver :: RootResolver IO () Query Undefined Undefined
rootResolver =
RootResolver
{ queryResolver = Query {deity},
mutationResolver = Undefined,
subscriptionResolver = Undefined
}
where
deity DeityArgs {name} =
pure
Deity
{ name = pure name,
power = pure (Just "Shapeshifting")
}
api :: ByteString -> IO ByteString
api = interpreter rootResolver

查看 morpheus-graphql-examples 以获取更复杂的 API。

Mu-Haskell 与 Mu-GraphQL

最新版本3 年前
星标325
许可证Apache 许可证 2.0

一个用于构建微服务 (gRPC、HTTP) 和 GraphQL API 的 Haskell 库。

使用类型级表示的 GraphQL 服务器的示例实现,该表示自动生成。

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
-- imports omitted for brevity...
graphql "Library" "library.graphql" -- all the magic happens here! 🪄🎩
-- ... a bit more code...
libraryServer :: SqlBackend -> ServerT ObjectMapping i Library ServerErrorIO _
libraryServer conn =
resolver
( object @"Book"
( field @"id" bookId,
field @"title" bookTitle,
field @"author" bookAuthor,
field @"imageUrl" bookImage
),
object @"Author"
( field @"id" authorId,
field @"name" authorName,
field @"books" authorBooks
),
object @"Query"
( method @"authors" allAuthors,
method @"books" allBooks
),
object @"Mutation"
( method @"newAuthor" newAuthor,
method @"newBook" newBook
),
object @"Subscription"
(method @"allBooks" allBooksConduit)
)
where
bookId :: Entity Book -> ServerErrorIO Integer
bookId (Entity (BookKey k) _) = pure $ toInteger k
-- ... more resolvers...

查看 我们的文档 以获取有关如何构建自己的 GraphQL 服务器的更多信息,以及 库示例 以获取更完整的端到端示例,其中包括用 Elm 编写的客户端!

graphql-w-persistent

星标10
许可证未知

一组完整的库工具,用于使用 SQL 抽象关系数据库模式,使用 GraphQL 查询,并返回 GraphQL 结果。

一次性设置:构建模式,作为微服务或在服务器内部署,使用 GraphQL 查询 SQL 数据库!

客户端

morpheus-graphql-client

最近发布10 个月前
星标400
许可证MIT 许可证

一个在 Haksell 中实现的强类型 GraphQL 客户端。

C / C++

工具

libgraphqlparser

最新版本6 年前
星标1k
许可证MIT 许可证

一个具有 C 和 C++ API 的 C++ GraphQL 查询语言解析器。

OCaml / Reason

服务器

ocaml-graphql-server

最新发布1 年前
星标1k
许可证MIT 许可证

用于 OCaml 和 Reason 的 GraphQL 服务器库。

Erlang

服务器

graphql-erlang

最新版本5 年前
星标313
许可证其他

Erlang 中的 GraphQL 实现。

Ballerina

服务器

ballerina-graphql

最新版本4 周前
星标144
许可证Apache 许可证 2.0

用于编写 GraphQL 服务的 Ballerina 标准库包。

要运行 ballerina-graphql hello world 服务器

  • 下载并安装 Ballerina 语言
  • 然后运行 bal run graphql_service.bal 来运行服务,在 graphql_service.bal 文件中使用以下代码
import ballerina/graphql;
service /graphql on new graphql:Listener(9090) {
resource function get hello() returns string {
return "Hello, world!";
}
}

功能#

  • 使用 Ballerina 的 servicelistener 模型构建,它们是 Ballerina 中的一等公民。
  • 支持通过 websocket 订阅(无需额外库)。
  • 支持文件上传。
  • 内置 GraphiQL 客户端。

客户端

ballerina-graphql

最新版本4 周前
星标144
许可证Apache 许可证 2.0

用于使用 GraphQL 服务的 Ballerina 标准库包。

要运行 ballerina-graphql 客户端

  • 下载并安装 Ballerina 语言
  • 然后运行 bal run graphql_client.bal 来运行服务,代码在 graphql_client.bal 文件中。
import ballerina/graphql;
import ballerina/io;
type Response record {
record { string hello; } data;
};
public function main() returns error? {
graphql:Client helloClient = check new ("localhost:9090/graphql");
string document = "{ hello }";
Response response = check helloClient->execute(document);
io:println(response.data.hello);
}

功能#

  • 依赖类型响应检索,使用 Ballerina 类型推断。
  • 支持自定义客户端生成。

Julia

客户端

Diana.jl

最新发布1 年前
Stars112
许可证MIT 许可证

一个 Julia GraphQL 服务器实现。

GraphQLClient.jl

最新发布1 年前
Stars46
许可证其他

一个 Julia GraphQL 客户端,用于与 GraphQL 服务器无缝集成。

  • 查询变异订阅,无需手动编写查询字符串(除非你想要!)。
  • 将响应直接反序列化为 Julia 类型。
  • 从 GraphQL 对象构建 Julia 类型
  • 使用内省来帮助查询。

快速入门#

使用 Julia 的包管理器安装。

using Pkg; Pkg.add("GraphQLClient")
using GraphQLClient

连接到服务器。

client = Client("https://countries.trevorblades.com")

从 GraphQL 对象构建 Julia 类型。

Country = GraphQLClient.introspect_object(client, "Country")

并查询服务器,将响应反序列化为这种新类型。

response = query(client, "countries", Vector{Country}, output_fields="name")

或者手动编写查询字符串。

query_string = """
{
countries{
name
}
}"""
response = GraphQLClient.execute(client, query_string)

R

服务器

ghql

最新发布4年前
Stars141
许可证其他

通用 GraphQL R 客户端。

Groovy

服务器

gorm-graphql

最新版本3 个月前
Stars80
许可证Apache 许可证 2.0

一个用于 GORM 的自动 GraphQL 模式生成器。

核心库 - GORM GraphQL 库提供功能,可以根据你的 GORM 实体生成 GraphQL 模式。除了将域类映射到 GraphQL 模式之外,核心库还提供“数据提取器”的默认实现,以通过执行模式来查询、更新和删除数据。

Grails 插件 - 除了核心库之外,GORM GraphQL Grails 插件

  • 提供一个控制器,根据其指南通过 HTTP 接收和响应 GraphQL 请求。

  • 在启动时生成模式,并使用 spring bean 配置,使其易于扩展。

  • 默认情况下,在开发中包含一个GraphiQL 浏览器。该浏览器可在 /graphql/browser 访问。

  • 覆盖默认数据绑定器,使用 Grails 提供的数据绑定

  • 提供一个 trait,使您的 GraphQL 端点的集成测试更容易

查看 文档 以了解更多信息。

GQL

最新发布1 年前
星标47
许可证Apache 许可证 2.0

GQL 是一个用于 GraphQL 的 Groove 库

Perl

服务器

graphql-perl

Stars70
许可证未知

GraphQL 参考实现的 Perl 移植版

Elm

客户端

库和命令行代码生成器,用于为 GraphQL 端点创建类型安全的 Elm 代码。

D

服务器

D 编程语言的 GraphQL 实现。

网关/超级图

WunderGraph

最新版本1 周前
星标2k
许可证Apache 许可证 2.0

WunderGraph 是一个开源 GraphQL 网关,能够组合 Apollo Federation、GraphQL、REST API、数据库、Kafka 等。

WunderGraph 将所有 API 组合成一个统一的 GraphQL API,并允许您将您的图公开为 安全且类型安全的 JSON-RPC API

要开始使用 WunderGraph,您可以使用 create-wundergraph-app 来引导一个新项目

npx create-wundergraph-app my-project -E nextjs-swr

在客户端,WunderGraph 的 JSON-RPC API 与 Next.js、SWR 和 React Query 等框架很好地集成,而在后端,我们能够利用“服务器端 GraphQL”的强大功能。在查询层处理身份验证、授权、验证、联接等。

mutation (
$name: String! @fromClaim(name: NAME)
$email: String! @fromClaim(name: EMAIL)
$message: String! @jsonSchema(pattern: "^[a-zA-Z 0-9]+$")
) {
createOnepost(
data: {
message: $message
user: {
connectOrCreate: {
where: { email: $email }
create: { email: $email, name: $name }
}
}
}
) {
id
message
user {
id
name
}
}
}

上面的查询要求用户经过身份验证,从 JWT 令牌中注入用户的姓名和电子邮件,并根据 JSON Schema 验证消息。

以下是一个示例,展示了如何使用 WunderGraph 的独特 联接功能 将来自两个不同 API 的数据组合到单个 GraphQL 响应中。

query (
$continent: String!
# the @internal directive removes the $capital variable from the public API
# this means, the user can't set it manually
# this variable is our JOIN key
$capital: String! @internal
) {
countries_countries(filter: { continent: { eq: $continent } }) {
code
name
# using the @export directive, we can export the value of the field `capital` into the JOIN key ($capital)
capital @export(as: "capital")
# the _join field returns the type Query!
# it exists on every object type so you can everywhere in your Query documents
_join {
# once we're inside the _join field, we can use the $capital variable to join the weather API
weather_getCityByName(name: $capital) {
weather {
temperature {
max
}
summary {
title
description
}
}
}
}
}
}

完整的 示例可以在 GitHub 上找到

通用

quicktype

Star11k
许可证Apache 许可证 2.0

为 TypeScript、Swift、golang、C#、C++ 等中的 GraphQL 查询生成类型。

GraphQL 代码生成器

最新发布3 周前
Star11k
许可证MIT 许可证

GraphQL 代码生成器,支持灵活的自定义插件和模板,例如 Typescript(前端和后端)、React Hooks、解析器签名等。

Schemathesis

最新版本2 周前
星标2k
许可证MIT 许可证

一个现代的 API 测试工具,用于使用 Open API 和 GraphQL 规范构建的 Web 应用程序。

通过 Docker 针对您的 GraphQL 端点运行 Schemathesis

docker run schemathesis/schemathesis \
run https://your.app.com/graphql

Schemathesis 将生成与您的 GraphQL 架构匹配的查询,并自动捕获服务器崩溃。生成的查询具有任意深度,并且可能包含输入架构中定义的任何 GraphQL 类型子集。它们会暴露代码中的边缘情况,这些情况在其他情况下不太可能被发现。

请注意,您可以使用任何编程语言编写您的应用程序;该工具将通过 HTTP 与其通信。

例如,在 https://bahnql.herokuapp.com/graphql 上运行上面的命令会发现运行 { search(searchTerm: "") { stations { name } } } 查询会导致服务器错误。

{
"errors": [
{
"message": "Cannot read property 'city' of undefined",
"locations": [
{
"line": 1,
"column": 28
}
],
"path": [
"search",
"stations"
]
}
],
"data": null
}

Microcks

星标1k
许可证Apache 许可证 2.0

开源 Kubernetes 原生工具,用于 API 模拟和测试

Microcks 是一个平台,用于将您的 API 和微服务资产(GraphQL 架构OpenAPI 规范AsyncAPI 规范gRPC protobufPostman 集合SoapUI 项目)在几秒钟内转换为实时模拟。

它还重用这些资产来针对您的 API 实现运行合规性和非回归测试。我们通过简单的 CLI 提供与 JenkinsGitHub ActionsTekton 和许多其他工具的集成。

gqt

星标455
许可证MIT 许可证

在终端中构建和执行 GraphQL 查询。

针对您的 GraphQL 端点运行 gqt。在直观的 TUI 中构建您的查询并执行它。来自服务器的响应将写入标准输出。

gqt -e https://your.app.com/graphql

GraphQL 防护

最新版本2 个月前
星标453
许可证MIT 许可证

Apollo GraphQL 和 Yoga / Envelop 服务器缺少的 GraphQL 安全层。

服务#

Webiny 允许您在 AWS Lambda 和 DynamoDB 之上快速构建 GraphQL API,并提供内置脚手架。Webiny 还包括一个现成的无头 GraphQL CMS,提供无代码体验。

Typetta 是一个用 TypeScript 编写的开源 ORM,旨在以类型化的方式允许所有主要 SQL 数据库(MySQL、PostgreSQL、Microsoft SQL Server、SQLLite3、CockroachDB、MariaDB、Oracle 和 Amazon Redshift)以及 NoSQL 数据库 MongoDB 无缝访问数据。

Tyk 是一款轻量级的开源 API 管理网关,它围绕 GraphQL 构建了完整的 API 生命周期管理,并拥有自己的用 Golang 编写的 GraphQL 引擎。Tyk 支持通过 通用数据图 (UDG) 以及 GraphQL 联合GraphQL 订阅 对多个 GraphQL 和/或 REST API 进行模式拼接。

一个 SaaS(软件即服务)内容管理系统,允许您使用强大的编辑工具创建内容,并通过 GraphQL 或 REST API 从任何地方访问内容。

基于您的数据源(REST 和数据库)、第三方 API 或任何组合创建无服务器 GraphQL API。无需自己编写 GraphQL 服务器,您可以通过编写 GraphQL 模式来声明性地定义所有内容。有关更多信息,请访问 https://www.stepzen.com/

下一代 Node.js 和 TypeScript ORM,内置数据加载器,可用于构建 GraphQL 后端。有关更多信息,请访问 https://prisma.org.cn/graphql

一个强大的多协议 API 客户端,具有 API 脚本、自动化、协作工作区以及对测试和开发 GraphQL API 的全面支持等功能。

一个 GraphQL 分析和监控服务,用于查找功能和性能问题。

一个无头 CMS(内容管理系统),将强大的内容个性化和调度功能与现代内容编辑体验和超快的 GraphQL/REST 内容交付 API 相结合。

Insomnia 是一款开源的跨平台 API 客户端,适用于 GraphQL、REST 和 gRPC。Insomnia 将易于使用的界面与身份验证助手、代码生成和环境变量等高级功能相结合。

Hygraph 是一个联邦内容平台,允许您真正组合您的堆栈。使用独特的内容联邦方法集成所有服务,并使用单个强大的 GraphQL API 在任何地方分发内容 - 到任何地方。

Hasura 连接到您的数据库和微服务,并立即为您提供一个可投入生产的 GraphQL API。

快速免费的安全扫描,可以在 GraphQL 端点上运行十几个测试。无需登录。

graphapi® 是一款安全的低代码 GraphQL-as-a-service 平台。基于输入数据模型,它会自动生成 GraphQL 架构、所有解析器和数据库堆栈。此外,它还提供了一个用户界面,允许团队管理其数据。有关更多信息,请访问 https://graphapi.com

轻松构建 GraphQL 后端。使用模式优先方法以声明方式构建您的后端。通过利用强大的指令和标量来加速开发并减少样板代码。

通过导入 gql 模式创建即时 GraphQL 后端。数据库将为您创建关系和索引,因此您可以在几秒钟内准备好查询,而无需编写任何数据库代码。无服务器定价,免费开始。

实时 GraphQL 安全和合规性。确保您的 GraphQL 端点已准备好投入生产。在开发过程中。无需配置。支持所有语言和框架。免费开始。

一个 Java 库,可以将 JPA 注释数据模型作为 GraphQL 服务公开到任何关系数据库。

Dgraph

Dgraph 是一个具有图形后端的原生 GraphQL 数据库。这意味着 Dgraph 不是基于现有数据库(如 Postgres)之上的接口,而是从头开始为 GraphQL 设计的。它针对速度和性能进行了优化,依赖于多个计算机科学突破以获得最佳结果。Dgraph Cloud 是一种完全托管的 GraphQL 后端服务,让您无需担心基础设施即可更快地迭代。

如果在 Linux 上本地运行而不是在 Dgraph Cloud 上运行,则安装步骤

docker pull dgraph/standalone
mkdir -p ~/dgraph
docker run -it -p 5080:5080 -p 6080:6080 -p 8080:8080 \
-p 9080:9080 -p 8000:8000 -v ~/dgraph:/dgraph --name dgraph \
dgraph/standalone:master

设置您的 GraphQL 模式

touch schema.graphql
nano schema.graphql
type Product {
id: ID!
name: String! @id
reviews: [Review] @hasInverse(field: about)
}
type Customer {
username: String! @id
reviews: [Review] @hasInverse(field: by)
}
type Review {
id: ID!
about: Product!
by: Customer!
comment: String @search(by: [fulltext])
rating: Int @search
}
curl -X POST localhost:8080/admin/schema --data-binary '@schema.graphql'

启动您最喜欢的 GraphQL 客户端,指向 https://127.0.0.1:8080/graphql 并运行变异和查询

mutation {
addProduct(input: [{ name: "Dgraph" }, { name: "Dgraph Cloud" }]) {
product {
id
name
}
}
addCustomer(input: [{ username: "TonyStark" }]) {
customer {
username
}
}
}
mutation {
addReview(
input: [
{
by: { username: "TonyStark" }
about: { name: "Dgraph" }
comment: "Fantastic, easy to install, worked great. Best GraphQL server available"
rating: 10
}
]
) {
review {
id
comment
rating
by {
username
}
about {
id
name
}
}
}
}
query {
queryReview(filter: { comment: { alloftext: "server easy install" }, rating: { gt: 5 } }) {
comment
by {
username
reviews(order: { desc: rating }, first: 10) {
about {
name
reviews(order: { asc: rating, first: 5 }) {
by { username }
comment
rating
}
}
rating
}
}
about {
name
}
}
}

ChilliCream 提供的具有丰富功能的 GraphQL IDE,可让您探索、管理和测试您的 GraphQL API。查看 这里

基于开源 Parse 平台的完全托管的 GraphQL 后端。存储和查询关系数据,运行云函数等等,通过 GraphQL API。免费开始。

全托管 GraphQL 服务,提供实时订阅、离线编程和同步,以及企业级安全功能和细粒度授权控制。

一种云服务,帮助您构建、验证、监控和保护组织的数据图。

Apache APISIX 是一款动态、实时、高性能的 API 网关,提供丰富的流量管理功能,例如负载均衡、动态上游、金丝雀发布、可观察性等。作为云原生 API 网关,Apache APISIX 在设计之初就已支持 GraphQL 语法。高效匹配请求中携带的 GraphQL 语句,可以过滤掉异常流量,进一步确保安全。更多信息,请访问 如何使用 API 网关 Apache APISIX 与 GraphQL 集成

一个 GraphQL API,用于查询和修改跨越 Salesforce、HubSpot、Microsoft Dynamics、Pipedrive 等多个 API 的数据。

Postman 的替代方案,支持直接编辑 GraphQL 查询并自动加载您的 GraphQL 架构。

想改进此页面?请查看 此处文档