Search code examples
graphqlpostmangraphql-jsconverterspostman-collection-runner

How to convert a GraphQL file to a Postman Collection?


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.


Solution

  • 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');
        }
    })