postmanlabs / postman-code-generators Goto Github PK
View Code? Open in Web Editor NEWCommon repository for all code generators shipped with Postman
License: Apache License 2.0
Common repository for all code generators shipped with Postman
License: Apache License 2.0
There is support for Java UniRest and Java OkHttp, but there is no support for Java Rest Assured which is widely used java library to test Rest APIs
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:
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.
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
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
$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
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 ;)
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.
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.
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.
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 ;-)
generate proxy setting in code snippet. for now, I Just need in
That will be great if this feature exists in postman. it helps me a lot of productivity
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.
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.)
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);
});
Is your feature request related to a problem? Please describe.
Rust is growing fast and gaining acceptance. Postman lacks Rust examples.
Describe the solution you'd like
New code generators in Rust, using Actix, Warp and/or Rocket crates.
Additional context
https://github.com/actix/actix
https://github.com/seanmonstar/warp
https://github.com/SergioBenitez/Rocket/tree/v0.4
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.
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.
Is your feature request related to a problem? Please describe.
Postman does not currently support apache bench code gen
Describe the solution you'd like
Add support for apache bench code gen. It would be very useful to have apache bench as one of the language options in the Generate Code Snippets pop up.
Additional context
https://paw.cloud/extensions/ApacheBenchmarkCodeGenerator
https://httpd.apache.org/docs/2.4/programs/ab.html
Generated snippet
response = requests.request("GET", url, headers=headers, data = payload, allow_redirects=False, allow_redirects=false)
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
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 -:
imports global keyword in require('shelljs/global');
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);
});
Add some level of exception handling(try-catch blocks) for functions inside lib
folder.
New Bug
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.
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.
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 URL
s/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
Describe the bug
All defined variables must use in GoLang but err
variable in this line not used.
Expected code snippet and corresponding request
We can add nil check on err
variable.
Related Line:
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));
});
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.
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.
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
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.
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.
Would love to see WordPress examples, which would typically use wp_remote_get
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.
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
Currently, the following files present inside npm
folder are bash scripts
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.
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.
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
Unexpected token 'header' in expression or statement.
At line:3 char:3
Unexpected token 'header' in expression or statement.
At line:4 char:3
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
+ 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 : 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 : 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
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.
Additional context
I would like to work on this issue.
Here is my request:
When I try to upload a file it works just file.
Code generation part is compleate nonsence:
The file should be read into memory and should not be part of the payload.
Here is documentation form python: https://2.python-requests.org//en/latest/user/quickstart/#post-a-multipart-encoded-file
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.
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:
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)
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.
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
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'))
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.