• Stars
    star
    3,339
  • Rank 13,411 (Top 0.3 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead-simple universal javascript GraphQL client.

graphqurl

oclif Version

Azure Pipelines Appveyor CI Downloads/week License

graphqurl is a curl like CLI for GraphQL. It's features include:

  • CLI for making GraphQL queries. It also provisions queries with autocomplete.
  • Run a custom GraphiQL, where you can specify request's headers, locally against any endpoint
  • Use as a library with Node.js or from the browser
  • Supports subscriptions
  • Export GraphQL schema

Made with ❀️ by Hasura


Graphqurl Demo

GraphiQL Demo

Subscriptions triggering bash


Table of contents

Installation

Steps to Install CLI

npm install -g graphqurl

Steps to Install Node Library

npm install --save graphqurl

Usage

CLI

Query

gq https://my-graphql-endpoint/graphql \
     -H 'Authorization: Bearer <token>' \
     -q 'query { table { column } }'

Auto-complete

Graphqurl can auto-complete queries using schema introspection. Execute the command without providing a query string:

$ gq <endpoint> [-H <header:value>]
Enter the query, use TAB to auto-complete, Ctrl+Q to execute, Ctrl+C to cancel
gql>

You can use TAB to trigger auto-complete. Ctrl+C to cancel the input and Ctrl+Q/Enter to execute the query.

GraphiQL

Open GraphiQL with a given endpoint:

gq <endpoint> -i

This is a custom GraphiQL where you can specify request's headers.

Subscription

Subscriptions can be executed and the response is streamed on to stdout.

gq <endpoint> \
   -q 'subscription { table { column } }'

Export schema

Export GraphQL schema to GraphQL or JSON format:

gq <endpoint> --introspect > schema.graphql

# json
gq <endpoint> --introspect --format json > schema.json

Command

$ gq ENDPOINT [-q QUERY]

Args

  • ENDPOINT: graphql endpoint (can be also set as GRAPHQURL_ENDPOINT env var)

Flag Reference

Flag Shorthand Description
--query -q GraphQL query to execute
--header -H request header
--variable -v Variables used in the query
--variablesJSON -n Variables used in the query as JSON
--graphiql -i Open GraphiQL with the given endpoint, headers, query and variables
--graphiqlHost -a Host to use for GraphiQL. (Default: localhost)
--graphiqlPort -p Port to use for GraphiQL
--singleLine -l Prints output in a single line, does not prettify
--introspect Introspect the endpoint and get schema
--format Output format for GraphQL schema after introspection. Options: json, graphql (Default: graphql)
--help -h Outputs the command help text
--version Outputs CLI version
--queryFile File to read the query from
--operationName Name of the operation to execute from the query file
--variablesFile JSON file to read the query variables from

Node Library

Using callbacks:

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer <token>'
  }
});

function successCallback(response, queryType, parsedQuery) {
  if (queryType === 'subscription') {
    // handle subscription response
  } else {
    // handle query/mutation response
  }
}

function errorCallback(error, queryType, parsedQuery) {
  console.error(error);
}

client.query(
  {
    query: 'query ($id: Int) { table_by_id (id: $id) { column } }',
    variables: { id: 24 }
  },
  successCallback,
  errorCallback
);

Using Promises:

For queries and mutations,

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer <token>'
  }
});

client.query(
  {
    query: 'query ($id: Int) { table_by_id (id: $id) { column } }',
    variables: { id: 24 }
  }
).then((response) => console.log(response))
 .catch((error) => console.error(error));

For subscriptions,

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer <token>'
  },
  websocket: {
    endpoint: 'wss://my-graphql-endpoint/graphql',
    onConnectionSuccess: () => console.log('Connected'),
    onConnectionError: () => console.log('Connection Error'),
  }
});

client.subscribe(
  {
    subscription: 'subscription { table { column } }',
  },
  (event) => {
    console.log('Event received: ', event);
    // handle event
  },
  (error) => {
    console.log('Error: ', error);
    // handle error
  }
)

API

createClient

The createClient function is available as a named export. It takes init options and returns client.

const { createClient } = require('graphqurl');
  • options: [Object, required] graphqurl init options with the following properties:

    • endpoint: [String, required] GraphQL endpoint
    • headers: [Object] Request header, defaults to {}. These headers will be added along with all the GraphQL queries, mutations and subscriptions made through the client.
    • websocket: [Object] Options for configuring subscriptions over websocket. Subscriptions are not supported if this field is empty.
      • endpoint: [String, ] WebSocket endpoint to run GraphQL subscriptions.
      • shouldRetry: [Boolean] Boolean value whether to retry closed websocket connection. Defaults to false.
      • parameters: [Object] Payload to send the connection init message with
      • onConnectionSuccess: [void => void] Callback function called when the GraphQL connection is successful. Please not that this is different from the websocket connection being open. Please check the followed protocol for more details.
      • onConnectionError: [error => null] Callback function called if the GraphQL connection over websocket is unsuccessful
      • onConnectionKeepAlive: [void => null]: Callback function called when the GraphQL server sends GRAPHQL_CONNECTION_KEEP_ALIVE messages to keep the connection alive.
  • Returns: [client]

Client

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql'
});

The graphqurl client exposeses the following methods:

  • client.query: [(queryoptions, successCallback, errorCallback) => Promise (response)]

    • queryOptions: [Object required]
      • query: [String required] The GraphQL query or mutation to be executed over HTTP
      • variables: [Object] GraphQL query variables. Defaults to {}
      • headers: [Object] Header overrides. If you wish to make a GraphQL query while adding to or overriding the headers provided during initalisations, you can pass the headers here.
    • successCallback: [response => null] Success callback which is called after a successful response. It is called with the following parameters:
      • response: The response of your query
    • errorCallback: [error => null] Error callback which is called after the occurrence of an error. It is called with the following parameters:
      • error: The occurred error
    • Returns: [Promise (response) ] This function returns the response wrapped in a promise.
      • response: response is a GraphQL compliant JSON object in case of queries and mutations.
  • client.subscribe: [(subscriptionOptions, eventCallback, errorCallback) => Function (stop)]

    • subscriptionOptions: [Object required]
      • subscription: [String required] The GraphQL subscription to be started over WebSocket
      • variables: [Object] GraphQL query variables. Defaults to {}
      • onGraphQLData: [(response) => null] You can optionally pass this function as an event callback
      • onGraphQLError: [(response) => null] You can optionally pass this function as an error callback
      • onGraphQLComplete: [() => null] Callback function called when the GraphQL subscription is declared as complete by the server and no more events will be received
    • eventCallback: [(response) => null] Event callback which is called after receiving an event from the given subscription. It is called with the following parameters:
      • event: The received event from the subscription
    • errorCallback: [error => null] Error callback which is called after the occurrence of an error. It is called with the following parameters:
      • error: The occurred error
    • Returns: [void => null] This is a function to stop the subscription

More Examples

Node Library

Queries and Mutations

Query example with variables

const { createClient } = require('graphqurl');

const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'x-access-key': 'mysecretxxx',
  },
});

client.query(
  {
    query: `
      query ($name: String) {
        table(where: { column: $name }) {
          id
          column
        }
      }
    `,
    variables: {
      name: 'Alice'
    }
  }
).then((response) => console.log(response))
 .catch((error) => console.error(error));

Subscriptions

Using promises,

const { createClient } = require('graphqurl');
const client = createClient({
  endpoint: 'https://my-graphql-endpoint/graphql',
  headers: {
    'Authorization': 'Bearer Andkw23kj=Kjsdk2902ksdjfkd'
  }
  websocket: {
    endpoint: 'wss://my-graphql-endpoint/graphql',
  }
})

const eventCallback = (event) => {
  console.log('Event received:', event);
  // handle event
};

const errorCallback = (error) => {
  console.log('Error:', error)
};

client.subscribe(
  {
    query: 'subscription { table { column } }',
  },
  eventCallback,
  errorCallback
)

CLI

Generic example:

gq \
     https://my-graphql-endpoint/graphql \
     -H 'Authorization: Bearer <token>' \
     -H 'X-Another-Header: another-header-value' \
     -v 'variable1=value1' \
     -v 'variable2=value2' \
     -q 'query { table { column } }'

Maintained with ❀️ by Hasura

More Repositories

1

graphql-engine

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
TypeScript
31,162
star
2

gitkube

Build and deploy docker images to Kubernetes using git push
Go
3,805
star
3

skor

Now part of Hasura GraphQL Engine. Listen to postgres events and forward them as JSON payloads to a webhook
C
1,246
star
4

learn-graphql

Real world GraphQL tutorials for frontend developers with deadlines!
JavaScript
1,177
star
5

gatsby-gitbook-starter

Generate GitBook style modern docs/tutorial websites using Gatsby + MDX
JavaScript
985
star
6

awesome-react-graphql

A curated collection of resources, clients and tools that make working with `GraphQL and React/React Native` awesome
738
star
7

eff

🚧 a work in progress effect system for Haskell 🚧
Haskell
547
star
8

react-check-auth

Add auth protection anywhere in your react/react-native app
JavaScript
530
star
9

3factor-example

Canonical example of building a 3factor app : a food ordering application
JavaScript
458
star
10

awesome-live-reloading

A curated collection of live-reloading / hot-reloading / watch-reloading tools for different languages and frameworks.
435
star
11

ra-data-hasura

react-admin data provider for Hasura GraphQL Engine
TypeScript
335
star
12

awesome-vue-graphql

A curated collection of resources, clients and tools that make working with `GraphQL and Vue.js` awesome
302
star
13

graphql-bench

A super simple tool to benchmark GraphQL queries
TSQL
263
star
14

hasura-ecommerce

TypeScript
246
star
15

pgdeltastream

Streaming Postgres logical replication changes atleast-once over websockets
Go
244
star
16

graphql-engine-heroku

Blazing fast, instant realtime GraphQL APIs on Postgres with fine grained access control, also trigger webhooks on database events.
Dockerfile
231
star
17

graphql2chartjs

graphql2chartjs reshapes your GraphQL data as per the ChartJS API.
JavaScript
222
star
18

hasura-aws-stack

A complete production ready 100% serverless stack on AWS with Hasura
JavaScript
215
star
19

json2graphql

From a JSON file to postgres-backed realtime GraphQL
JavaScript
200
star
20

3factor

3factor app is an architecture pattern for modern fullstack apps. 3factor apps are fast to build and are highly scalable.
SCSS
181
star
21

client-side-graphql

147
star
22

hasura-k8s-stack

A feature-complete Hasura stack on Kubernetes
JavaScript
138
star
23

hasura-actions-examples

Examples of handling custom business logic with Hasura Actions
JavaScript
135
star
24

awesome-angular-graphql

A curated collection of resources, clients and tools that make working with `GraphQL and Angular` awesome
132
star
25

gqless-movies-demo

A movies app using Hasura and gqless
TypeScript
127
star
26

awesome-fluent-graphql

Awesome list of fluent GraphQL clients & examples
TypeScript
106
star
27

graphiql-online

Explore your GraphQL APIs with headers
JavaScript
90
star
28

kubeformation

Create declarative cluster specifications for your managed Kubernetes vendor (GKE, AKS)
Go
86
star
29

data-dictionary

TypeScript
85
star
30

firebase2graphql

Move from Firebase realtime db to instant GraphQL APIs on Postgres
JavaScript
81
star
31

jwt-guide

TypeScript
79
star
32

nodejs-graphql-subscriptions-boilerplate

Boilerplate to setup GraphQL subscriptions in your nodejs code
JavaScript
78
star
33

pacha

Connect your private data to LLMs
PLpgSQL
74
star
34

graphql-serverless

Example boilerplates for GraphQL backends hosted on serverless platforms
Go
71
star
35

graphql-parser-hs

A GraphQL query parser for Haskell
Haskell
59
star
36

sphinx-graphiql

Sphinx plugin that adds a GraphiQL directive so that you can embed an interactive GraphQL query explorer in your docs
JavaScript
57
star
37

kriti-lang

A minimal JSON templating language
Haskell
55
star
38

schema-stitching-examples

JavaScript
44
star
39

gitkube-example

An example repo to be used with gitkube: git push to deploy on to Kubernetes
HTML
43
star
40

graphql-backend-benchmarks

GraphQL performance benchmarks across Hasura, Postgraphile and Prisma
Shell
42
star
41

comment-progress

Notify progress by commenting on GitHub issues, pull requests, and commits :octocat: πŸ’¬
JavaScript
42
star
42

local-development

[Deprecated] Run Hasura locally on your computer
37
star
43

rxdb-hasura-demo

An Offline first todo app
JavaScript
37
star
44

monad-validate

(NOTE: REPOSITORY MOVED TO NEW OWNER: https://github.com/lexi-lambda/monad-validate) A Haskell monad transformer library for data validation
Haskell
32
star
45

pod42

Python
31
star
46

gitlab-graphql

Install gitlab and expose the gitlab api's over GraphQL
JavaScript
29
star
47

codegen-assets

TypeScript
27
star
48

ndc-hub

Go
26
star
49

data-hub

Explore data sources from a native GraphQL API, database schemas to custom code contributed by the community.
PLpgSQL
26
star
50

pg-client-hs

A low level Haskell library to connect to postgres
Haskell
25
star
51

yelp-clone-react

A Yelp clone built using React + GraphQL + Hasura
JavaScript
24
star
52

github-integration-starter

Try out Hasura's GitHub Integration on Cloud Projects using the examples in this repo.
24
star
53

template-gallery

Repository containing schema sharing packages.
PLpgSQL
24
star
54

authz-workshop

TSQL
23
star
55

hasura-cloud-preview-apps

TypeScript
22
star
56

graphql-schema-stitching-demo

Schema Stitching Example with Hasura GraphQL + MetaWeather API
JavaScript
22
star
57

hasura-discord-docs-bot

PLpgSQL
21
star
58

ndc-typescript-deno

Instant Hasura Native Data Connector by writing Typescript Functions
TypeScript
21
star
59

ndc-spec

NDC Specification and Reference Implementation
Rust
20
star
60

issues

Dump and sync org wide issues into postgres and visualise with metabase.
Python
19
star
61

realm-pg-sync

The realm-pg-sync microservice
JavaScript
18
star
62

graphql-data-specification

A specification for Data APIs with GraphQL
Haskell
18
star
63

imad-app

Base repository for IMAD course application.
JavaScript
18
star
64

ndc-postgres

Hasura v3 Data Connector for PostgreSQL
Rust
18
star
65

react-apollo-todo

A todo app with react, apollo demonstrating graphql queries, mutations and subscriptions.
CSS
17
star
66

architect-graphql-workshop

JavaScript
16
star
67

continuous-backup

Postgres wal-e continuous backup system
Shell
16
star
68

preview-actions

Starter kit to try out actions
JavaScript
16
star
69

auth-ui-kit

Web UI Kit for Hasura Authentication
JavaScript
15
star
70

graphql-example-apps

PLpgSQL
14
star
71

smooth-checkout-buildkite-plugin

All the things you need during a Buildkite checkout 🧈 πŸͺ
Shell
14
star
72

js-sdk

JavaScript
14
star
73

cloud-functions-boilerplates

Boilerplates for cloud functions (AWS Lambda, Google Cloud Functions, Azure Cloud Functions, Zeit, etc.) that work in conjunction with Hasura GraphQL Engine's event triggers
JavaScript
14
star
74

graphql-subscriptions-benchmark

TypeScript
13
star
75

sample-apps

TypeScript
12
star
76

demo-apps

Config to deploy Hasura demo apps using Docker Compose
HTML
12
star
77

github-bot

Hasura's own GitHub bot πŸ€–
JavaScript
11
star
78

generator-hasura-web

JavaScript
11
star
79

open-data-domain-specification

Rust
11
star
80

sqlite-dataconnector-agent

SQLite Data Connector Agent for Hasura GQL Engine. Please note that this repository is a mirror. We will still accept PRs, but will have to mirror them to our upstream repo.
TypeScript
11
star
81

ndc-sdk-typescript

NDC SDK for TypeScript
TypeScript
11
star
82

smooth-secrets-buildkite-plugin

A buildkite plugin to setup ssh keys and env secrets for your pipelines 🧈 πŸ”’
Shell
11
star
83

chat-app-android

Java
10
star
84

custom-resolvers-boilerplate

A boilerplate for writing custom resolvers with Hasura GraphQL Engine
JavaScript
10
star
85

reactathon-workshop

10
star
86

go-buildkite-dsl

Write Buildkite configs in Go πŸͺ πŸ“
Go
9
star
87

android-sdk

The Android SDK for Hasura
Java
9
star
88

sample-auth-webhook

Sample auth webhooks for the Hasura GraphQL engine
JavaScript
9
star
89

generator-hasura-node

JavaScript
9
star
90

graphql-asia-workshop

JavaScript
9
star
91

supergraph-io

Content for the supergraph.io website
HTML
8
star
92

graphql-on-various-pg

Hasura's GraphQL engine on various Postgres systems/providers
Shell
8
star
93

cli-plugins-index

Shell
8
star
94

graphql-weather-api

A simple GraphQL express weather api server boilerplate
JavaScript
8
star
95

supergraph-top-n-challenge

JavaScript
8
star
96

ddn-sample-app

TypeScript
8
star
97

ndc-nodejs-lambda

Write NodeJS TypeScript functions and easily expose them in your Hasura DDN project
TypeScript
7
star
98

haskell-docker-builder

Package haskell binaries as docker images
Makefile
7
star
99

graphql-engine-install-manifests

Various installation manifests for Hasura's GraphQL Engine
Shell
7
star
100

laravel-todo-hge

A sample Laravel app with an auth webhook
PHP
7
star