How to convert a GraphQL file to a Postman Collection?

1.7k views Asked by At

I want to convert a GraphQL file to a Postman collection. I tried with a JavaScript library to do that (https://www.npmjs.com/package/graphql-to-postman).

But I'm getting the following error:

Unhandled Rejection (TypeError): Cannot set property 'includeDeprecatedFields' of undefined

function convert() {
    var postmanJson = fileReader.result,
    fileDownload = require('js-file-download');
    const graphQlToPostman = require('graphql-to-postman');

    const collection = graphQlToPostman.convert(postmanJson);

    fileDownload(
        JSON.stringify(collection),
        'postman collection',
    );
}

This is the function where I used the library.

2

There are 2 answers

0
UdaraWanasinghe On BEST ANSWER

To convert graphql to postman collection, first you need graphql schema. Graphql schema can be downloaded by running introspection query on the graphql server end point. Here is how to do it.

  1. Install graphql-cli

    npm i -g apollo
    
  2. Download schema from the graphql server

    apollo schema:download --endpoint=http://localhost:4000/graphql schema.json
    

Convert schema into graphql collection

const fs = require('fs')
const converter = require('graphql-to-postman')

const schema = fs.readFileSync('./schema.json')
converter.convert({
    type: 'string',
    data: schema.toString(),
}, {}, async function (error, result) {
    if (error) {
        log.error('Conversion failed')
    } else {
        const outputData = result.output[0].data
        fs.writeFileSync('output-collection.json', JSON.stringify(outputData))
        console.log('Conversion success');
    }
})
0
Mohammed Ali On

I've built an easy-to-use command-line tool that allows you to automatically generate your Postman collection from your GraphQL endpoint. (https://www.npmjs.com/package/graphql-testkit)

It also comes with out-of-the-box support to control the maximum depth and add headers to all the requests in the collection.

Simply doing this, after replacing the endpoint, and adding or removing headers based on your requirement will auto-generate a Postman Collection with support for variables.

graphql-testkit \ 
--endpoint=https://api/spacex.land/graphql\ 
--header="Authorization:123,x-ws-system-id=10" \
--maxDepth=4