Skip to content

Instantly share code, notes, and snippets.

@idkjs
Last active June 20, 2020 20:04
Show Gist options
  • Save idkjs/4cc5a640bd380c6a5c709bb5e0689c5e to your computer and use it in GitHub Desktop.
Save idkjs/4cc5a640bd380c6a5c709bb5e0689c5e to your computer and use it in GitHub Desktop.

get-graphql-schema npm version

Fetch and print the GraphQL schema from a GraphQL HTTP endpoint. (Can be used for Relay Modern.)

Note: Consider using graphql-cli instead for improved workflows.

Install

npm install -g get-graphql-schema

Usage

  Usage: get-graphql-schema [OPTIONS] ENDPOINT_URL > schema.graphql

  Fetch and print the GraphQL schema from a GraphQL HTTP endpoint
  (Outputs schema in IDL syntax by default)

  Options:
    --header, -h    Add a custom header (ex. 'X-API-KEY=ABC123'), can be used multiple times
    --json, -j      Output in JSON format (based on introspection query)
    --version, -v   Print version of get-graphql-schema

Usage With Header from terminal

  # watch your formatting

  export BEARER_TOKEN=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qS
  export ENDPOINT_URL=https://api.endpoint.com/learn/graphql
  npx get-graphql-schema ENDPOINT_URL -j -h "Authorization=Bearer $BEARER_TOKEN" > graphql_schema.json

Help & Community Slack Status

Join our Slack community if you run into issues or have questions. We love talking to you!

#!/bin/bash
# echo $BEARER_TOKEN
npx get-graphql-schema https://hasura.io/learn/graphql -j -h "Authorization=Bearer $BEARER_TOKEN" > graphql_schema.json
// if all esle fails add this file and run:
// export BEARER_TOKEN=<token>
// node scripts/sendIntrospectionQuery https://endpoint.url/graphql --headers "Authorization: Bearer ${BEARER_TOKEN}"
#!/usr/bin/env node
var argv = require("yargs")
.usage('Usage: $0 <url> [--headers "key:value"]')
.command("url", "URL of the GraphQL endpoint", { alias: "url" })
.required(1, "URL is required")
.option("H", {
alias: "headers",
describe: "Additional Headers to send with introspection query",
type: "array",
coerce: arg => {
let additionalHeaders = {};
for (const header of arg) {
const separator = header.indexOf(":");
const name = header.substring(0, separator).trim();
const value = header.substring(separator + 1).trim();
if (!(name && value)) {
throw new Error('Headers should be specified as "Name: Value"');
}
additionalHeaders[name] = value;
}
return additionalHeaders;
}
})
.help("?")
.alias("?", "help")
.example("$0 https://example.com/graphql", "Get GraphQL Schema")
.example(`$0 https://example.com/graphql --headers "Authorisation: <token>"`, "Get GraphQL Schema with Authorisation header").argv;
var request = require("request");
var fs = require("fs");
var introspectionQuery = `
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}`;
const requestOptions = {
json: true,
body: { query: introspectionQuery },
headers: { "user-agent": "node.js", ...argv.headers }
};
request.post(argv._[0], requestOptions, function(error, response, body) {
if (error) {
console.error("Could not send introspection query: ", error);
process.exit(1);
}
if (response.statusCode !== 200) {
console.error("Non-ok status code from API: ", response.statusCode, response.statusMessage);
process.exit(1);
}
var result = JSON.stringify(body, null, 2);
fs.writeFileSync("graphql_schema.json", result, { encoding: "utf-8" });
});
@idkjs
Copy link
Author

idkjs commented Jun 20, 2020

Graphql Client Setup

Finally, you need a graphql_schema.json in the root of your project so that the GraphQL queries and mutations are type checked against it. To get graphql_schema.json,

  1. Go to https://hasura.io/learn/graphql/graphiql and login
  2. Copy the JWT from headers:
    graphiql-jwt-copy
  3. Run this command from the root of your project:
npx send-introspection-query https://hasura.io/learn/graphql --header "Authorization: Bearer <JWT>"
  npx get-graphql-schema https://hasura.io/learn/graphql -j --header "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9" > graphql_schema.json",
npx send-introspection-query https://hasura.io/learn/graphql --header "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9"

https://github.com/prisma-labs/get-graphql-schema/blob/2e8732322ba52158aa6bb163de3d7107a041cc52/src/bin.ts#L14

  --header, -h    Add a custom header (ex. 'X-API-KEY=ABC123'), can be used multiple times
 npx get-graphql-schema https://hasura.io/learn/graphql -j --header 'Authorization=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9'
# seem to work but request denied
npx get-graphql-schema https://hasura.io/learn/graphql -j -h 'Authorization=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9'

# seem to work using old graphql_ppx but request denied
 npx send-introspection-query https://hasura.io/learn/graphql --headers "Authorization: Bearer ${BEARER_TOKEN}"

# these seem to work but request denied
~/Downloads/re-boilerplate/app-boilerplate update-reason*
❯ node scripts/sendIntrospectionQuery https://hasura.io/learn/graphql --headers "Authorization: Bearer ${BEARER_TOKEN}"

❯ npx get-graphql-schema https://hasura.io/learn/graphql -j -h 'Authorization=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9'
Error: [
  {
    "extensions": {
      "path": "$",
      "code": "access-denied"
    },
    "message": "Authentication hook unauthorized this request"
  }
]

This works. Token was wrong because didnt copy whole thing.

~/Downloads/re-boilerplate/app-boilerplate update-reason*
❯ export BEARER_TOKEN=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9.eyJodHRwczovL2hhc3VyYS5pby9qd3QvY2xhaW1zIjp7IngtaGFzdXJhLWRlZmF1bHQtcm9sZSI6InVzZXIiLCJ4LWhhc3VyYS1hbGxvd2VkLXJvbGVzIjpbInVzZXIiXSwieC1oYXN1cmEtdXNlci1pZCI6ImF1dGgwfDVkMWNiZmQzMTcxZDJkMGM3ZTRlYTk4MCJ9LCJuaWNrbmFtZSI6ImFhcm1hbmQuaW5ib3giLCJuYW1lIjoiYWFybWFuZC5pbmJveEBnbWFpbC5jb20iLCJwaWN0dXJlIjoiaHR0cHM6Ly9zLmdyYXZhdGFyLmNvbS9hdmF0YXIvMzM3Zjg0YWUwYzMyYmRhNWE0ZDllY2JkMTVkMzZlYjc_cz00ODAmcj1wZyZkPWh0dHBzJTNBJTJGJTJGY2RuLmF1dGgwLmNvbSUyRmF2YXRhcnMlMkZhYS5wbmciLCJ1cGRhdGVkX2F0IjoiMjAyMC0wNi0yMFQxODozMjozNS43MTNaIiwiaXNzIjoiaHR0cHM6Ly9ncmFwaHFsLXR1dG9yaWFscy5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NWQxY2JmZDMxNzFkMmQwYzdlNGVhOTgwIiwiYXVkIjoiUDM4cW5GbzFsRkFRSnJ6a3VuLS13RXpxbGpWTkdjV1ciLCJpYXQiOjE1OTI2ODEyNzUsImV4cCI6MTU5MjcxNzI3NSwiYXRfaGFzaCI6Im1Za1p6ejd6LTFOa2VhMWxjTlRqTWciLCJub25jZSI6IjYxVFE3ZlNSNGhUZC5yQ0M0UTNUeGh5b1ZqMHh3RExCIn0.IR5e6rg8XDWE9yzDeB_oaCLkmUxcsdQlrBl5M6dzDEMXqN90lRKT_lmswe_nlfTKsHCIWf5Kv5t2GLmZO6jQ28JHc8W3v0bQ9VJIWDkfUTTii09oWuaGLdHiHa8cuv9KXqKxJ2Ymt3g-F-mlwEZ4rfqy-hN00fZpMy1MgnRGk0IpXPL8MRh6XISCiOqmqLpzrbY8yPWNng1gbKAYB5shYi68NGj0bSfmJWB5xWR0lwtjjVupXK62bZEjSVdO2HGop01qahHUDvBNUEn2-WPA-eeEeXdhDtWpv91TRnLbzJsbqkrIIkvMyw45fQJ3MaJ7tuVpV7JmxnHp1naaFTY9fQ

~/Downloads/re-boilerplate/app-boilerplate update-reason*
❯ node scripts/sendIntrospectionQuery https://hasura.io/learn/graphql --headers "Authorization: Bearer $BEARER_TOKEN"
~/Downloads/re-boilerplate/app-boilerplate update-reason*# ALSO....formatting again
npx get-graphql-schema https://hasura.io/learn/graphql -j -h "Authorization=Bearer $BEARER_TOKEN"
npx get-graphql-schema https://hasura.io/learn/graphql -j -h "Authorization=Bearer $BEARER_TOKEN" > graphql_schema.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment