graphqurl
curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead-simple universal javascript GraphQL client.
Top Related Projects
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
A reference implementation of GraphQL for JavaScript
The Fullstack Tutorial for GraphQL
Quick Overview
GraphQURL is a command-line tool and Node.js library for making GraphQL requests. It allows users to send GraphQL queries and mutations from the terminal or integrate them into Node.js applications. GraphQURL simplifies the process of interacting with GraphQL APIs, making it easier for developers to test and work with GraphQL endpoints.
Pros
- Easy-to-use command-line interface for quick GraphQL queries
- Supports both queries and mutations
- Can be used as a Node.js library for integration into applications
- Provides options for authentication and custom headers
Cons
- Limited documentation and examples
- May not support all advanced GraphQL features
- Less actively maintained compared to some other GraphQL clients
- Lacks a graphical user interface for visual query building
Code Examples
- Basic GraphQL query:
const { query } = require('graphqurl');
const result = await query({
endpoint: 'https://api.example.com/graphql',
query: `
query {
users {
id
name
}
}
`
});
console.log(result.data);
- GraphQL mutation with variables:
const { query } = require('graphqurl');
const result = await query({
endpoint: 'https://api.example.com/graphql',
query: `
mutation ($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
email
}
}
`,
variables: {
name: 'John Doe',
email: 'john@example.com'
}
});
console.log(result.data);
- Using custom headers for authentication:
const { query } = require('graphqurl');
const result = await query({
endpoint: 'https://api.example.com/graphql',
headers: {
'Authorization': 'Bearer YOUR_TOKEN_HERE'
},
query: `
query {
privateData {
id
content
}
}
`
});
console.log(result.data);
Getting Started
To use GraphQURL, first install it via npm:
npm install -g graphqurl
For command-line usage:
gq https://api.example.com/graphql -q "query { users { id name } }"
For Node.js usage, install it as a dependency:
npm install graphqurl
Then use it in your code as shown in the code examples above.
Competitor Comparisons
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
Pros of Apollo Client
- More comprehensive and feature-rich GraphQL client with advanced caching capabilities
- Extensive ecosystem with integrations for popular frameworks like React, Vue, and Angular
- Robust developer tools and debugging support
Cons of Apollo Client
- Steeper learning curve due to its extensive feature set
- Larger bundle size, which may impact performance for smaller applications
- More complex setup process compared to simpler alternatives
Code Comparison
Apollo Client:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
GraphQURL:
const { query } = require('graphqurl');
const result = await query({
query: '{ users { id name } }',
endpoint: 'https://api.example.com/graphql'
});
Key Differences
- Apollo Client is a full-featured GraphQL client library, while GraphQURL is a lightweight command-line tool and JavaScript library for making GraphQL requests
- Apollo Client offers advanced caching and state management, whereas GraphQURL focuses on simplicity and ease of use
- Apollo Client is better suited for large-scale applications, while GraphQURL is ideal for quick prototyping and simple GraphQL interactions
Use Cases
- Choose Apollo Client for complex applications requiring advanced features and integrations
- Opt for GraphQURL when you need a simple, lightweight solution for making GraphQL requests or for command-line interactions
A reference implementation of GraphQL for JavaScript
Pros of graphql-js
- More comprehensive and feature-rich GraphQL implementation
- Widely adopted and maintained by the GraphQL Foundation
- Extensive documentation and community support
Cons of graphql-js
- Steeper learning curve for beginners
- Requires more setup and configuration for basic usage
- Larger package size and potential performance overhead
Code Comparison
graphql-js:
const { graphql, buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const rootValue = { hello: () => 'Hello world!' };
graphql({ schema, source: '{ hello }', rootValue }).then((response) => {
console.log(response);
});
graphqurl:
const { query } = require('graphqurl');
query({
query: '{ hello }',
endpoint: 'https://api.example.com/graphql',
}).then((response) => {
console.log(response);
});
Key Differences
- graphql-js is a full GraphQL implementation, while graphqurl is a lightweight client-side tool
- graphqurl focuses on simplifying GraphQL queries from the command line or Node.js
- graphql-js provides more flexibility and control over schema definition and execution
- graphqurl offers a more straightforward approach for quick GraphQL interactions
The Fullstack Tutorial for GraphQL
Pros of howtographql
- Comprehensive learning resource for GraphQL
- Covers multiple languages and frameworks
- Community-driven with contributions from experts
Cons of howtographql
- Not a tool for direct GraphQL interactions
- Requires more time investment to learn GraphQL concepts
Code comparison
howtographql (React + Apollo example):
const GET_POSTS = gql`
query {
posts {
id
title
}
}
`;
function Posts() {
const { loading, error, data } = useQuery(GET_POSTS);
// ... render logic
}
graphqurl:
gq https://my-graphql-endpoint.com/graphql \
-q 'query { posts { id title } }'
Key differences
- Purpose: howtographql is an educational resource, while graphqurl is a command-line tool for GraphQL queries
- Audience: howtographql targets developers learning GraphQL, graphqurl is for developers working with GraphQL APIs
- Functionality: howtographql provides tutorials and examples, graphqurl offers a quick way to execute GraphQL queries
Use cases
- howtographql: Best for developers new to GraphQL or looking to expand their knowledge
- graphqurl: Ideal for rapid testing and exploration of GraphQL APIs from the command line
Both projects serve different purposes in the GraphQL ecosystem, with howtographql focusing on education and graphqurl on practical API interaction.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
graphqurl
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 :heart: by Hasura
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 asGRAPHQURL_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
andmutations
.
- response: response is a GraphQL compliant JSON object in case of
- queryOptions: [Object required]
-
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
- subscriptionOptions: [Object required]
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 :heart: by Hasura
Top Related Projects
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
A reference implementation of GraphQL for JavaScript
The Fullstack Tutorial for GraphQL
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot