Coder Social home page Coder Social logo

postmanlabs / postman-code-generators Goto Github PK

View Code? Open in Web Editor NEW
973.0 37.0 342.0 7.47 MB

Common repository for all code generators shipped with Postman

License: Apache License 2.0

JavaScript 99.23% Shell 0.74% PHP 0.03%
code-generators postman-collection postman converter

postman-code-generators's Introduction


Manage all of your organization's APIs in Postman, with the industry's most complete API development environment.

Supercharge your API workflow.
Modern software is built on APIs. Postman helps you develop APIs faster.

postman-code-generators Build Status

This module converts a Postman SDK Request Object into a code snippet of chosen language.

Every code generator has two identifiers: language and variant.

  • language of a code generator is the programming language in which the code snippet is generated.
  • variant of a code generator is the methodology or the underlying library used by the language to send requests.

List of supported code generators:

Language Variant
C libcurl
C# HttpClient
C# RestSharp
cURL cURL
Dart http
Go Native
HTTP HTTP
Java OkHttp
Java Unirest
JavaScript Fetch
JavaScript jQuery
JavaScript XHR
Kotlin OkHttp
NodeJs Axios
NodeJs Native
NodeJs Request
NodeJs Unirest
Objective-C NSURLSession
OCaml Cohttp
PHP cURL
PHP Guzzle
PHP pecl_http
PHP HTTP_Request2
PowerShell RestMethod
Python http.client
Python Requests
R httr
R RCurl
Rust Reqwest
Ruby Net:HTTP
Shell Httpie
Shell wget
Swift URLSession

Table of contents

Getting Started

To install postman-code-generators as your dependency

$ npm install postman-code-generators

To get a copy on your local machine

$ git clone https://github.com/postmanlabs/postman-code-generators.git

Prerequisite

To run any of the postman-code-generators, ensure that you have NodeJS >= v8. A copy of the NodeJS installable can be downloaded from https://nodejs.org/en/download/package-manager.

Usage

Using postman-code-generators as a Library

There are three functions that are exposed in postman-code-generators: getLanguageList, getOptions, and convert.

getLanguageList

This function returns a list of supported code generators.

Example:
var codegen = require('postman-code-generators'), // require postman-code-generators in your project
    supportedCodegens = codegen.getLanguageList();
    console.log(supportedCodegens);
    // output:
    // [
    //   {
    //     key: 'nodejs',
    //     label: 'NodeJs',
    //     syntax_mode: 'javascript',
    //     variant: [
    //       {
    //         key: 'Requests'
    //       },
    //       {
    //         key: 'Native'
    //       },
    //       {
    //         key: 'Unirest'
    //       }
    //     ]
    //   },
    //   ...
    // ]

getOptions

This function takes in three parameters and returns a callback with error and supported options of that code generator.

  • language - language key from the language list returned from getLanguageList function
  • variant - variant key provided by getLanguageList function
  • callback - callback function with first parameter as error and second parameter as array of options supported by the codegen.

A typical option has the following properties:

  • name - Display name
  • id - unique ID of the option
  • type - Data type of the option. (Allowed data types: boolean, enum, positiveInteger)
  • default - Default value. The value that is used if this option is not specified while creating code snippet
  • description - User friendly description.
Example:
var codegen = require('postman-code-generators'), // require postman-code-generators in your project
    language = 'nodejs',
    variant = 'Request';

    codegen.getOptions(language, variant, function (error, options) {
      if (error) {
        // handle error
      }
      console.log(options);
    });
// output: 
//     [
//     {
//       name: 'Set indentation count',
//       id: 'indentCount',
//       type: 'positiveInteger',
//       default: 2,
//       description: 'Set the number of indentation characters to add per code level'
//     },
//     {
//       name: 'Set indentation type',
//       id: 'indentType',
//       type: 'enum',
//       availableOptions: ['Tab', 'Space'],
//       default: 'Space',
//       description: 'Select the character used to indent lines of code'
//     },
//     ...
//   ];

convert

This function takes in five parameters and returns a callback with error and generated code snippet

  • language - lang key from the language list returned from getLanguageList function
  • variant - variant key provided by getLanguageList function
  • request - Postman-SDK Request Object
  • options - Options that can be used to configure generated code snippet. Defaults will be used for the unspecified attributes
  • callback - callback function with first parameter as error and second parameter as string for code snippet
Example:
var codegen = require('postman-code-generators'), // require postman-code-generators in your project
    sdk = require('postman-collection'), // require postman-collection in your project
    request = new sdk.Request('https://www.google.com'),  //using postman sdk to create request 
    language = 'nodejs',
    variant = 'request',
    options = {
        indentCount: 3,
        indentType: 'Space',
        trimRequestBody: true,
        followRedirect: true
    };
codegen.convert(language, variant, request, options, function(error, snippet) {
    if (error) {
        //  handle error
    }
    //  handle snippet
});

Development

Installing dependencies

This command will install all the dependencies in production mode.

$ npm install;

To install dev dependencies also for all codegens run:

$ npm run deepinstall dev; 

Testing

To run common repo test as well as tests (common structure test + individual codegen tests) for all the codegens

$ npm test; 

To run structure and individual tests on a single codegen

$ npm test <codegen-name>;
# Here "codege-name" is the folder name of the codegen inside codegens folder

Packaging

To create zipped package of all codegens

$ npm run package;

Note: The zipped package is created inside each codegen's folder.

To create zipped package of a single codegen

$ npm run package <codegen-name>

Contributing

Please take a moment to read our contributing guide to learn about our development process. Open an issue first to discuss potential changes/additions.

License

This software is licensed under Apache-2.0. Copyright Postman, Inc. See the LICENSE.md file for more information.

postman-code-generators's People

Contributors

abhijitkane avatar abhijitpostman avatar ajwad-shaikh avatar aman-v-singh avatar amymariaparker2401 avatar dependabot[bot] avatar dm-francis avatar erfemega avatar gabrielsroka avatar husseinhj avatar kevinswiber avatar liyingxiu avatar lokot0k avatar luistejedas avatar maxxfrazer avatar nikhilmuz avatar nilsjr avatar r3dsm0k3 avatar richardgroves avatar sahilchoudhary22 avatar sastava007 avatar shreys7 avatar snyk-bot avatar someshkoli avatar umeshp7 avatar vibhorgupta-gh avatar vinibrsl avatar vshingala avatar web-flow avatar webholik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postman-code-generators's Issues

add pure Java generator

Is your feature request related to a problem? Please describe.
Postman comes with a few code generators for HTTP Requests.

For Java devs, there are generators for the Libraries OkHttp and Unirest, but there is no code generator for Java without any libraries

Describe the solution you'd like
A new code generator generating java code (with URLs/HttpURLConnection and HttpsURLConnection).

Additional context
https://docs.oracle.com/javase/8/docs/api/java/net/URL.html
https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html
https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/HttpsURLConnection.html

PR template needed

Is your feature request related to a problem? Please describe.
Currently, there's no proper format to follow while creating the PR which leads to a lot of confusion for the reviewers to know what exactly you have changed and what needs to be reviewed. This issue should be treated with the utmost priority.
You can see a lot of PRs with no such description defining the changes that have been made.
image

Describe the solution you'd like
I would suggest using a template for the pull request covering basic checks like

  • Description

  • Changes you made

  • Screenshot/ CodeSnippet

  • Test Configuration

  • Follow up

Additional context

NodeJs - Request now depreciated?

Perhaps replacing the "NodeJS - Request" Code Snippet with Node-Fetch or Axios? If this is something that's okay to do, I can see about making a pr for it.

Inconsistent semicolon usage in nodejs/unirest

Seen in 0.0.9

var unirest = require('unirest');
var req = unirest('GET', 'httpbin.org/get')
.end(function (res) { 
  if (res.err) console.log(res.err);
  console.log(JSON.stringify(res.body));
});

Dependency Management by maven

Is your feature request related to a problem? Please describe.
Dependency management should be robust. Inspired by PR #187.

Describe the solution you'd like
Something like maven should be used for dependency management rather than hardcoding library itself or varying links for the library. Refer Maven

Additional context
Currently, we are hardcoding binaries and jar in a zip for managing dependency for java codegens like okhttp etc which is difficult to manage and bumping version is not that easy and for single dependency change, entire zip is committed causing larger commit size as zip file is committed as a whole in binary, not on line basis. Same is for updating dependencies.

Support ES6 syntax for Node { Unirest, Native, Request }

Is your feature request related to a problem? Please describe.
It is cumbersome to change syntax to make use of ES6 features in each request.

Describe the solution you'd like
Expose a code generator setting for the Node Framework that enables ES6 syntax

Additional context
For example:

var request = require('request');
var options = {
  'method': 'GET',
  'url': '{{url}}/hourdata/:id?hour={{hour}}',
  'headers': {
  }
};
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});

becomes

const request = require('request');
let options = {
  'method': 'GET',
  'url': '{{url}}/hourdata/:id?hour={{hour}}',
  'headers': {
  }
};
request(options, (error, response) => { 
  if (error) throw new Error(error);
  console.log(response.body);
});

(This is just an example. I understand that there will be use cases that require a more un-opinionated syntax.)

Please allow manual editing and saving to published docs (and avoid code gen from overwriting it)

Describe the bug
I am interested in the python code generator.
I would like to edit the code snippet manually myself and totally disable any interference by the auto code generator (that keeps overriding what I have manually copy-pasted in). If there is a way that this can be done, then I would be very keen to know. Thanks

To Reproduce
Body has this raw json:

{
    "outputs": [
        {
            "value": 0,
            "script_pubkey": "6a0548656c6c6f"
        },
        {
            "value": 100,
            "script_pubkey": "76a914fc746b833ca84043e0c7d606de8ecc4b7f3b7cd688ac"
        }
    ],
    "password": "test",
    "utxo_preselection": true
}

Expected code snippet and corresponding request
I want it to look something like this:

import requests

url = "http://127.0.0.1:9999/v1/stn/dapp/wallets/my_wallet.sqlite/1/txs/create_and_broadcast"

payload = { "outputs": [{"value": 0,
                         "script_pubkey": "6a0548656c6c6f"},
                        {"value": 100,
                         "script_pubkey": "76a914fc746b833ca84043e0c7d606de8ecc4b7f3b7cd688ac"}],
            "password": "test",
            "utxo_preselection": True}

headers = {'Content-Type': 'application/json'}

response = requests.request("POST", url, headers=headers, json=payload)

print(response.text.encode('utf8'))

Screenshots
Instead, it looks like this:

import requests

url = "http://127.0.0.1:9999/v1/stn/dapp/wallets/my_wallet.sqlite/1/txs/create_and_broadcast"

payload = "{\n    \"outputs\": [\n        {\n            \"value\": 0,\n            \"script_pubkey\": \"6a0548656c6c6f\"\n        },\n        {\n            \"value\": 100,\n            \"script_pubkey\": \"76a914fc746b833ca84043e0c7d606de8ecc4b7f3b7cd688ac\"\n        }\n    ],\n    \"password\": \"test\",\n    \"utxo_preselection\": true\n}"
headers = {
'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.text.encode('utf8'))

Lint checking support on CI

Describe the bug
CI Script doesn't checks for lint issues while passing tests to check those we have to manually run lint-test in each codegen.

To Reproduce
run npm run lint-test on root, it will say no such script is there.

Expected code snippet and corresponding request
Commit passed even lint tests were not passing.

Screenshots
Not Applicable

Additional context
There should be a centralized lint checking script to check lint in each codegen recursively and that should run on Travis. while checking for tests.

Adding eslint in system tests

All code-generators have their own eslint check but there are no eslint for lib, test, npm and index.js.
Add eslint checks to the root files and folders apart from codegen folder.

Please add pm.sendRequest code snippet generator

Is your feature request related to a problem? Please describe.
Currently, we have around 1200 requests per workspace(we have 3 workplaces). Some of these requests are needed for flow control and since the number of such requests becomes bigger and bigger we decided to move these methods inside dependent requests(Pre-request Script and Tests section with pm.sendRequest )

Describe the solution you'd like
We would like to add one more code snippet generator which will output script with postman pm.sendRequest code.
This will give an easier and faster way of constructing scripts that can be used in Pre-request and Test sections.

Additional context

Code Generation for Javascript Node/JQuery

Your code generator for Node and JQuery is very good at the top, then tails away, for example at the start, this is good:

var https = require('https');

var options = {
  'method': 'POST',
  'hostname': ....
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });
...

However, this code is not so good:

var postData =  "{\n\tFieldName: 'data'\n}";
req.write(postData);
req.end();

May I suggest that this last bit uses proper JSON objects rather than strings which are simply yuk!

Even this JQuery code:

var settings = {
  "url": "https://postman.com/security/authenticate",
  "method": "POST",
  ...
  "data": "{\r\n\tFullName: '{{FullName}}',\r\n\tPassword: '{{Password}}'\r\n}"
};

Should be re-written as:

var credentials = {
    FullName: '{{FullName}}',
    Password: '{{Password}}'
};
var sJSON = JSON.stringify(credentials);

var settings = {
  "url": "https://postman.com/security/authenticate",
  "method": "POST",
  ...
  "data": sJSON
};

Much easier to read, agree?

Everything else is coming along nicely ;-)

Add Groovy language in Generate Code Snippets

Hello,

It would be very useful to have Groovy as one of the language options in the Generate Code Snippets pop up. I have been trying to use the Javascript code snippets, but they aren't formatted quite right for my application using Groovy script and I am having to edit and troubleshoot too much. Thank you.

For cURL escaping of body content, single quotes should be used to improve readability

The Postman app, without these code generators enabled, will escape the JSON body for a cURL request using single-quotes, which makes the body easily readable when copy/pasting the cURL example into docs or scripts. For example, here is what the normal Postman app might shoe for a cURL request that includes some JSON:

curl -X POST \
  https://example.com/api/command \
  -H 'Accept: application/json' \
  -H 'Authorization: Basic TzJbGNtdA==' \
  -H 'Content-Type: application/json' \
  -H 'X-Request-ID: 1b3d12ad-e2f5-442e-99bb-bbea58936683' \
  -d '{
    "action": "query",
    "target": {
        "features": [
            "versions",
            "profiles",
            "pairs"
        ]
    }
}
'

Note that it is using single-quotes to pass the Headers and Body content to the cURL command-line. As such, there is very little backslash escaping and readability is high. Furthermore, by not adding all the double-quote escapes to the JSON body content, I can copy/paste it directly into something else, since it is just JSON (and not JSON with a bunch of weird escaping, which is not valid JSON).

If I enable this experimental code generator, the result is decidedly less readable, since the code-generators cURL support chooses to use double-quotes, causing much more unnecessary escaping of the JSON:

curl -X POST "https://example.com/api/command" \
    -H "Authorization: Basic TzJbGNtdA==" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "X-Request-ID: 1b3d12ad-e2f5-442e-99bb-bbea58936683" \
    -d "{
    \"action\": \"query\",
    \"target\": {
        \"features\": [
            \"versions\",
            \"profiles\",
            \"pairs\"
        ]
    }
}"

If I copy/paste this JSON body content into jsonlint.com, you will see that it is no longer valid JSON due to all the extra backslash escaping.

As such, I'd like to revert the code-generators back to using the single-quote for sanitizing the headers and body content. I have a fix for this and will submit a pull request in the next couple weeks for review.

A form-data POST request has random escaped characters in the generated snippet

For Swift URLSession, a formdata request gives the following request:

let paramName = param["key"]!
		body += "--\(boundary)\r\n"
		body += "Content-Disposition:form-data; name=\"\(paramName)\""
		if let paramValue = param["value"] {
			body += "\r\n\r\n\(paramValue)\r\n"
		} else {
			body += "; filename=\"{Insert_File_Name}\"\r\n"
			  + "Content-Type: \"{Insert_File_Content_Type}\"\r\n\r\n{Insert_File_Content}\r\n"
		}

Not sure why the \r\n is required here.

Inconsistent semicolon usage in nodejs/request snippet

Seen in 0.0.9

var request = require('request');
var fs = require('fs')
var options = {
  'method': 'GET',
  'url': 'httpbin.org/get',
  'headers': {
  }
}
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});

[PowerShell] The body parameter of Invoke-RestMethod should be null, not an emtpy string when using Get requests.

Describe the bug
When doing a Get request, with an empty body and using the "PowerShell - RestMethod" code snippet, an error will be raised as the Invoke-Request method is improperly called.

To Reproduce

  1. Create a Get request to any ressource, say "example.com". The code generated will be:
$body = ""

$response = Invoke-RestMethod 'https://example.com/' -Method 'GET' -Headers $headers -Body $body
$response | ConvertTo-Json

The error returned by Powershell is the following:

Invoke-RestMethod : コンテンツ本体をこの verb-type では送信できません。
発生場所 行:3 文字:6
+ $a = Invoke-RestMethod 'https://example.com/' -Method 'GET' -Headers  ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod], ProtocolViolationException
    + FullyQualifiedErrorId : System.Net.ProtocolViolationException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Expected code snippet and corresponding request
This snippet instead works:

$body = $null

$response = Invoke-RestMethod 'https://example.com/' -Method 'GET' -Headers $headers -Body $body
$response | ConvertTo-Json

Additional context
Version of postman-code-generators/Postman app: 7.14.0

Build on Travis CI failing on most of PR's

Describe the bug
I am a beginner and solved my first issue and made PR but build failed for that PR, then I observe most of PR are failing and checked details on Travis CI and by observing terminal output I think this is due to the exactly same reason for each PR.

To Reproduce
Steps to reproduce the behavior:

  1. Do Some Changes on the forked repository.
  2. Make Pull Request.
  3. Checks would be failed due to build failed on Travis CI.

Expected code snippet and corresponding request
I have tried to solve it and think it is due to the address of the maven repository i.e http://central.maven.org as it results in NOT FOUND.

Screenshots
Capture
Capture2
Capture3

http://central.maven.org

Capture4

Inconsistent script closing in php

In php/curl snippets, there's a closing ?> element, which is absent from php/pecl_http.

Seen in 0.0.9

Let's remove it from all php snippets - it's too small a change to add an option for.

Convert bash scripts(.sh files) to javascript files

Currently, the following files present inside npm folder are bash scripts

  • ci-requirements.sh
  • package.sh
  • test.sh
  • zip.sh

Change these bash scripts to javascript files, so that it becomes platform agnostic, i.e. works well on Windows, Linux or macOS. This can be achieved using the node's shelljs module.
See deepinstall.js file present in npm folder for reference.

Add support for QCObjects serviceLoader that is OOP oriented

Is your feature request related to a problem? Please describe.
It is needed an OOP oriented client in JavaScript to call microservices in the front-end side as well as the backend without the need to refactor the code.

Describe the solution you'd like
QCObjects is supporting that by the use of a serviceLoader helper that is wrapping the caller in the front-end as well as the backend using the same code pattern.

Additional context
Below is a code example that is working in the browsers as well as in node environment:

Class('MyTestService',Service,{
    name:'myservice',
    external:true,
    cached:false,
    method:'GET',
    headers:{'Content-Type':'application/json'},
    url:'https://api.github.com/orgs/QuickCorp/repos',
    withCredentials:false,
    _new_:()=>{
      // service instantiated
    },
    done:()=>{
      // service loaded
    }
});
// creating the OOP service client instance and loading it with serviceLoader at once
var service = serviceLoader(New(MyTestService,{
  data:{param1:1}
})).then(
  (successfulResponse)=>{
    // This will show the service response as a plain text
    console.log(successfulResponse.service.template);
  },
  (failedResponse)=>{

  });

QCObjects is being used by thousands of companies around the world since a few months ago (see npm stats ) and has been featured by British Herald as today, the most advanced framework for modern software development

Curl code from postman doesn't work

I created request at postman, tested it, all works fine, then I clicked on Code button at the right top corner, copied CURL code, and tried to use it in Windows Shell and got the errors

`At line:2 char:3

  • --header 'x-pr-tenantid: 2720F16E-1E5B-4AA5-93CB-6169E36B5C9E' \
  • ~
    Missing expression after unary operator '--'.
    At line:2 char:3
  • --header 'x-pr-tenantid: 2720F16E-1E5B-4AA5-93CB-6169E36B5C9E' \

Unexpected token 'header' in expression or statement.
At line:3 char:3

  • --header 'x-pr-apikey: <<>> ...
  • ~
    Missing expression after unary operator '--'.
    At line:3 char:3
  • --header 'x-pr-apikey: <<>> ...

Unexpected token 'header' in expression or statement.
At line:4 char:3

  • --header 'Authorization: Bearer <> ...
  • ~
    Missing expression after unary operator '--'.
    At line:4 char:3
  • --header 'Authorization: Bearer <> ...

Unexpected token 'header' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator`

Then I changed --header on -h and got the new ones

`Invoke-WebRequest : A positional parameter cannot be found that accepts argument '--request'.
At line:1 char:1

  • curl --location --request GET 'http://localhost:60513//sip/transactio ...
  •   + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
      + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
    
    

-h : The term '-h' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:2 char:1

  • -h 'x-pr-tenantid: 2720F16E-1E5B-4AA5-93CB-6169E36B5C9E' \
  • ~~
    • CategoryInfo : ObjectNotFound: (-h:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException

-h : The term '-h' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:3 char:1

  • -h 'x-pr-apikey: <<>> ...
  • ~~
    • CategoryInfo : ObjectNotFound: (-h:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException

-h : The term '-h' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:4 char:1

  • -h 'Authorization: Bearer <> ...
  • ~~
    • CategoryInfo : ObjectNotFound: (-h:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException`

Add depcheck

Depcheck is a tool for analyzing the dependencies in a project to see: how each dependency is used, which dependencies are useless, and which dependencies are missing from package.json and present in code.
Add depcheck integration to this project.
Reference: https://www.npmjs.com/package/depcheck

Fixture is not able to find the file path in case of formdataFileCollection

Describe the bug
The formdataFileCollection fixture is not able to locate the exact path where Newman is trying to upload the files when testing the codegens locally.

To Reproduce
Steps to reproduce the behavior:
Run npm test nodejs-request

Expected code snippet and corresponding request
This can be solved by making the test.sh script to first create the required files with sample data and then running addPathToFormdataFile.js file.

Screenshots
image

Additional context
I would like to work on this issue.

Extra commas are added when requestTimeout option is set to non zero value in nodejs request

Seen in 0.0.9

var request = require('request');
var fs = require('fs');
var options = {
  'method': 'GET',
  'url': 'https://postman-echo.com/headers',
  'headers': {
    'my-sample-header': 'Lorem ipsum dolor sit amet',
    'not-disabled-header': 'ENABLED'
  },
  timeout: 1000,,
  followRedirect: false
};
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});
var request = require('request');
var fs = require('fs');
var options = {
  'method': 'GET',
  'url': 'https://postman-echo.com/headers',
  'headers': {
    'my-sample-header': 'Lorem ipsum dolor sit amet',
    'not-disabled-header': 'ENABLED'
  },
  timeout: 1000,
};
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});

Improper escaping of body in cURL code generated for graphql request.

Getting the following error on running the generated cURL code snippet:

-bash: !: event not found
> 
{"errors":[{"message":"A query attribute must be specified and must be a string."}]}

Steps to reproduce.

  • Create a graphql query with at least one variable.
  • Generate cURL code snippet (Experimental Codegen).
  • Run generated code snippet.

Below is an example of generated code snippet: (I have removed the bearer token from below).
Generated By Postman:

curl -X POST "https://api.github.com/graphql" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer <<BEARER-TOKEN>>" \
    -d "{\"query\":\"query ($repoName: String!){\\n    repository (name: $repoName, owner: \\\"postmanlabs\\\") {\\n        issue (number: 1475) {\\n            id\\n            url\\n            bodyText\\n            labels (first: 10) {\\n                edges {\\n                    node {\\n                        name\\n                    }\\n                }\\n            }\\n        }\\n    }\\n}\",\"variables\":{\"repoName\":\"postman-app-support\"}}"

If the data in the above code snippet is replaced with:

 '{"query":"query ($repoName: String!){\n    repository (name: $repoName, owner: \"postmanlabs\") {\n        issue (number: 1475) {\n            id\n            url\n            bodyText\n            labels (first: 10) {\n                edges {\n                    node {\n                        name\n                    }\n                }\n            }\n        }\n    }\n}","variables":{"repoName":"postman-app-support"}}'

It works as expected.

Incorrect handling of single quotes in path

Describe the bug
A clear and concise description of what the bug is.
Clearly mention the code-generators that are affected by this issue.

Node-js Native, Nodejs-unirest do not resolve url correctly.

To Reproduce
Steps to reproduce the behavior:

Add a single quote in query params and generate code in "New Code Generation mode" in App.

Expected code snippet and corresponding request
If you have a working code snippet that you think solves your problem, please add it here:
Also, add the request.json for which this code snippet was generated.

Single quotes must be escaped.

Screenshots
If applicable, add screenshots to help explain your problem. Please make sure the screenshot does not contain any sensitive information such as API keys or access tokens.
For example you could add the screenshot of the snippet/request builder from Postman app.

Screenshot 2019-11-25 at 12 03 38 PM

Screenshot 2019-11-25 at 12 04 13 PM

Additional context
If you have any reference material which might help us debug the problem please add it here:
Add any other context about the problem here.
Version of postman-code-generators/Postman app:

Form-data POST request doesn't work as expected in csharp-restsharp

The below is the snippet generated for form data request:

var client = new RestClient("https://postman-echo.com/post");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddParameter("a", "b");
request.AddParameter("c", "d");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Copy pasting this snippet and executing it actually sends the data as application/x-www-form-urlencoded instead of multipart/form-data.

Incorrect code generated for JQuery when multiple headers of the same name are present.

Describe the bug
A clear and concise description of what the bug is.
Clearly mention the code-generators that are affected by this issue.

Incorrect code generated for JQuery when multiple headers of the same name are present.

To Reproduce
Steps to reproduce the behavior:
Add a request with two headers of the same key

Expected code snippet and corresponding request
If you have a working code snippet that you think solves your problem, please add it here:
Also, add the request.json for which this code snippet was generated.

Screenshots
If applicable, add screenshots to help explain your problem. Please make sure the screenshot does not contain any sensitive information such as API keys or access tokens.
For example you could add the screenshot of the snippet/request builder from Postman app.
Screenshot 2019-11-12 at 12 07 24 PM

Additional context
If you have any reference material which might help us debug the problem please add it here:
Add any other context about the problem here.
Version of Postman app: 7.11.0

dart support in code generator

Additional context
dart is backbone for many webapps and specially flutter framework which will take the lead in few years, better to be on the train ;)

User-Agent header set incorrectly in case of C#

Describe the bug
Affected code-generator: csharp-restsharp
The problem is clearly described in this issue of RestSharp: restsharp/RestSharp#787
In a nutshell, the code-generator currently sets the User-Agent like this:

request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0");

But it's not effective at all, see issue referenced above. The solution is from the same issue as well. The correct way to set it is on the client level, like this:

client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"

To Reproduce
Generate C# code for a request where the User-Agent header is set, then execute the generated code. Observe that the User-Agent is set to RestSharp x.x.x.x instead of the one in the generated code.

Python - Requests generated code doesn't work

Description: When running the code generator for Python - Requests, it generated a script that gets a 400 response doing a POST to ArcGI :
b'{"error":{"code":400,"error":"invalid_request","error_description":"client_id not specified","message":"client_id not specified","details":[]}}'

Reproduce: Create a POST request to https://www.arcgis.com/sharing/rest/oauth2/token using:
'client_id': "your_client_id",
'client_secret': "your_client_secret",
'grant_type': "client_credentials"
Then use the code generation for Python - Requests and try to run the script

Expected code snippet and corresponding request
The fix in the python generated code was to change the data variable called in:
response = requests.request("POST", url, headers=headers, data = payload, files = files)
to instead say (data => params):
response = requests.request("POST", url, headers=headers, params=payload, files=files)

Screenshots
Screen Shot 2020-03-14 at 7 21 48 PM
Screen Shot 2020-03-14 at 7 22 33 PM

Use of lodash.js in node codegens

Is your feature request related to a problem? Please describe.
i was going through the source code and found the lodash.js file in lib of node modules. it contains the basic functions that already in node but defining it again in lodash.js and using it in the main code seems a little off. for eg in lodash.js

const map = function(array, element, callback)

which can be also written as follow
const Array = Array.prototype
Array.map.call(array, element, callback)`

or simply
array.map() or array.forEach() etc

without lodash file.

Describe the solution you'd like
I would like to suggest to keep only those function like .isEmpty() which are not node implementation, implement other function like(.map, .filter) normally without lodash.

content is not correct encode

image
image

content should be urlencoded,but now is %uxxx, so my api get request params is like
{"content":"%u4E2D%u56FD"}

not the original string

Removing global import

Is your feature request related to a problem? Please describe.
Adding this feature does not affect code except reducing "global" words from codegen's npm directories

Describe the solution you'd like
We don't require Global import for shelljs in codegen's npm directories
Files likes -:

  1. test.js,
  2. test-lint.js
  3. test-newman.js

imports global keyword in require('shelljs/global');

Additional context
pstcd1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.