To run a ballerina-graphql
client:
bal run graphql_client.bal
to run the service, with this code in the graphql_client.bal
file: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);
}
Linq2GraphQL generates C# classes from the GraphQL schema and and togheter with the nuget package Linq2GraphQL.Client it makes it possible to query the server using Linq expressions.
A simple query that will get the first 10 orders with the primitive properties of orders and the connected customer
var orders = await sampleClient
.Query
.Orders(first: 10)
.Include(e => e.Orders.Select(e => e.Customer))
.Select(e => e.Orders)
.ExecuteAsync();
An example mutation where we add a new customer and return the Customer Id.
var customerId = await sampleClient
.Mutation
.AddCustomer(new CustomerInput
{
CustomerId = Guid.NewGuid(),
CustomerName = "New Customer",
Status = CustomerStatus.Active
})
.Select(e=> e.CustomerId)
.ExecuteAsync();
Strawberry Shake removes the complexity of state management and lets you interact with local and remote data through GraphQL.
You can use Strawberry Shake to:
client.GetHero
.Watch(ExecutionStrategy.CacheFirst)
.Subscribe(result =>
{
Console.WriteLine(result.Data.Name);
})
The ZeroQL is a high-performance C#-friendly GraphQL client. It supports Linq-like syntax, and doesn’t require Reflection.Emit or expressions. As a result, at runtime provides performance very close to a raw HTTP call.
You can use ZeroQL to:
var userId = 10;
var response = await qlClient.Query(q => q
.User(userId, o => new
{
o.Id,
o.FirstName,
o.LastName
}));
genqlient is a Go library to easily generate type-safe code to query a GraphQL API. It takes advantage of the fact that both GraphQL and Go are typed languages to ensure at compile-time that your code is making a valid GraphQL query and using the result correctly, all with a minimum of boilerplate.
genqlient provides:
interface{}
.Apollo Kotlin (formerly known as Apollo Android) is a GraphQL client with support for Android, Java8+, iOS and Kotlin multiplatform in general. It features:
GraphQL Kotlin provides a set of lightweight type-safe GraphQL HTTP clients. The library provides Ktor HTTP client and Spring WebClient based reference implementations as well as allows for custom implementations using other engines. Jackson and kotlinx-serialization type-safe data models are generated at build time by the provided Gradle and Maven plugins.
To generate Jackson models that will be used with GraphQL Kotlin Spring WebClient, add following to your Gradle build file:
// 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 = "http://localhost:8080/graphql"
// package for generated client code
packageName = "com.example.generated"
}
}
By default, GraphQL Kotlin plugins will look for query files under src/main/resources
. Given HelloWorldQuery.graphql
sample query:
query HelloWorldQuery {
helloWorld
}
Plugin will generate classes that are simple POJOs implementing GraphQLClientRequest interface and represent a GraphQL request.
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
}
}
We can then execute our queries using target client.
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 = "http://localhost:8080/graphql")
runBlocking {
val helloWorldQuery = HelloWorldQuery()
val result = client.execute(helloWorldQuery)
println("hello world query result: ${result.data?.helloWorld}")
}
}
See graphql-kotlin client docs for additional details.
GQty is a query builder, a query fetcher and a cache manager solution all-in-one.
You interact with your GraphQL endpoint via Proxy objects. Under the hood, GQty captures what is being read, checks cache validity, fetch missing contents and then updates the cache for you.
Start using GQty by simply running our interactive codegen:
# npm
npx @gqty/cli
# yarn
yarn dlx @gqty/cli
# pnpm
pnpm dlx @gqty/cli
GQty also provides framework specific integrations such as @gqty/react
and @gqty/solid
, which can be installed via our CLI.
The example below installs and initializes the GraphQLBox client with a persisted cache and debugging enabled.
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)
npm install graphql-hooks
First you’ll need to create a client and wrap your app with the provider:
import { GraphQLClient, ClientContext } from "graphql-hooks"
const client = new GraphQLClient({
url: "/graphql",
})
function App() {
return (
<ClientContext.Provider value={client}>
{/* children */}
</ClientContext.Provider>
)
}
Now in your child components you can make use of 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>
)
}
fetch
.Relay is a JavaScript framework for building data-driven React applications.
urql
is a GraphQL client that exposes a set of helpers for several frameworks.
It’s built to be highly customisable and versatile so you can take it from getting started with your first GraphQL project
all the way to building complex apps and experimenting with GraphQL clients.
@urql/exchange-graphcache
Install with Julia’s package manager
using Pkg; Pkg.add("GraphQLClient")
using GraphQLClient
Connect to a server
client = Client("https://countries.trevorblades.com")
Build a Julia type from a GraphQL object
Country = GraphQLClient.introspect_object(client, "Country")
And query the server, deserializing the response into this new type
response = query(client, "countries", Vector{Country}, output_fields="name")
Alternatively write the query string manually
query_string = """
{
countries{
name
}
}"""
response = GraphQLClient.execute(client, query_string)
Install Ariadne Codegen:
$ pip install ariadne-codegen
Create queries.graphql
file:
mutation CreateToken($username: String!, $password: String!) {
createToken(username: $username, password: $password) {
token
errors {
field
message
}
}
}
Add [ariadne-codegen]
section to your pyproject.toml
:
[ariadne-codegen]
queries_path = "queries.graphql"
remote_schema_url = "http://example.com/graphql/"
Generate client:
$ ariadne-codegen
And use it in your Python projects:
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
graphql_query is complete GraphQL query string builder for python. With graphql_query you can The documentation for graphql_query can be found at https://denisart.github.io/graphql-query.
$ pip install graphql_query
Code for the simple query
{
hero {
name
}
}
it is
from graphql_query import Operation, Query
hero = Query(name="hero", fields=["name"])
operation = Operation(type="query", queries=[hero])
print(operation.render())
"""
query {
hero {
name
}
}
"""
For generation of the following query
query Hero($episode: Episode, $withFriends: Boolean!) {
hero(episode: $episode) {
name
friends @include(if: $withFriends) {
name
}
}
}
we have
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 client library, wrapped around pydantic classes for type validation, provides a safe and simple way to query data from a GraphQL API.
Features:
pip3 install pydantic-graphql
Here’s an example of a qlient hello world.
first install the library:
pip install qlient
Create a swapi_client_example.py
file with this content:
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}}
Close the file and run it using python:
python swapi_client_example.py
A client library for rust that generates queries from types you provide, verifying that the types match the shape of your schema.
It provides a generator to bootstrap types from existing GraphQL queries.
Usage example:
#[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");
}
Usage example
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(())
}
An example of defining a GraphQL query and running it with caliban
:
// 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
SwiftGraphQL is a Swift code generator and a lightweight GraphQL client. It lets you create queries using Swift, and guarantees that every query you create is valid.
The library is centered around three core principles:
🚀 If your project compiles, your queries work. 🦉 Use Swift in favour of GraphQL wherever possible. 🌳 Your application model should be independent of your schema.
Here’s a short preview of the SwiftGraphQL code
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]
}
}