I'm getting some troubles when trying to make a post request to an API made with swagger 2.0 (not by me).
I've imported a collection to postman, and when i perform a post request it works perfect. However in Node.js it outputs a 400 error with swagger library, and a 500 with axios.
Heres the schema that the collection provides in postman:
{
"workflowFunctionID": 1,
"workflowActionParameters": [
{
"name": "Description",
"value": "Probando y wea2",
"workflowFunctionParameterId": 2
},
{
"name": "Price",
"value": "25000",
"workflowFunctionParameterId": 3
}
]
}
As i mentioned it works perfectly. And this is the current code that am using Node.js:
main = async() => {
try {
const token = await acquireTokenWithClientCredentials(RESOURCE, CLIENT_APP_Id, CLIENT_SECRET, AUTHORITY);
const request = {
url: `${WORKBENCH_API_URL}/api/v1/contracts?workflowId=1&contractCodeId=1&connectionId=1`,
method: "POST",
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token.access_token}` },
body: {
workflowActionInput: {
workflowFunctionID: 1,
workflowActionParameters: [{
"name": "description",
"value": "cualkier wea"
},
{
"name": "price",
"value": "20000000"
}
]
}
}
}
let res = await Swagger.http(request);
console.log(res);
}
catch (err) {
console.error(err);
}
}
main();
How should i pass the body/form-data to the post request, or maybe using another package or code? Thanks in advance for any help.
When you have api running in postman, just see this button named "code" i marked with black
click on this button
select language as node.js
It will show you code in node.js for that api, just copy that code and paste where required.
Here i am attaching picture kindly see this
Related
I am trying to implement axios POST to itop, everything works fine using POSTMAN for me to hard code "title, description, name and first name". Basically at the first start I want to make it like a webpage to input data and then submit the data to itop using POST.
Instead of me manually adding the required parameters, I want to grab the parameters from a form. As for the current script that I have, it said the URL is wrong because the actual URL should be like this instead of below (actual URL from postman: http://test.com/itop/webservices/rest.php?version=1.3&json_data={\n "operation": "core/create",\n "comment": "Synchronization from blah...",\n "class": "UserRequest",\n "output_fields": "id, friendlyname",\n "fields":\n {\n "org_id": "SELECT Organization WHERE name = \"TEST\"",\n "caller_id":\n {\n "name": "name",\n "first_name": "first_name"\n },\n "title": "Test",\n "description": "Test Ticket"\n }\n}')
Here is the code, this code will give out 404 because the request is not correct
app.post('/form-submit', (req, res) => {
let bodyData = {
"operation": "core/create",
"class": "UserRequest",
"output_fields": "id, friendlyname",
"fields": {
"org_id": "SELECT Organization WHERE name = 'TEST'",
},
"caller_id": {
"name": req.body.name,
"first_name": req.body.first_name
},
"title": req.body.title,
"description": req.body.description,
}
let axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic c2FtdWVsLmNoYW5AbHlasdfasdZS5jb206W04wemgxa2FyMV0=',
'Cookie': 'itop-ffb5bc6b0d3aasdfa53a36b=g20efh3399am02aq7v8tif1b7l'
},
}
axios.post('http://test.com/itop/webservice/rest.php?version=1.3&json_data=', bodyData, axiosConfig)
.then(function (response) {
console.log("Ticket created:" + response.data)
})
.catch(function (error) {
console.log(error)
})
})
Thanks ahead for any insight provided
I am new to this swagger and i created a small demo project in node-js to see how swagger will really works. I created 5 api's which 4 are working perfectly and when it comes to PUT api I am getting error ,but when i tried in postman it is working. Please look at the code below.
export let updateUser = async(req: Request, resp: Response) => {
try{
const use = await User.findById(req.params.id);
use.name = req.body.name;
// use.email = req.body.email;
const a1 = await use.save();
resp.json("successfully updated");
} catch(err) {
resp.send('Error')
}
}
this is the api which is calling above method in app.ts
//put-request
app.put('/user/update/:id',controller.updateUser);
This is the the swagger json of put API
"/user/update/{id}": {
"put": {
"tags": [
"Update-Api"
],
"summary": "Update-user",
"description": "To updatre the particular user",
"operationId": "updateUser",
"consumes": ["application/json"],
"parameters":[
{
"name":"Id",
"in":"path",
"description":"enter the id of the user",
"required":true,
"type":"string"
},
{
"name":"body",
"in":"body",
"description":"Enter the update value",
"required":true,
"$schema": {
"type": "#/definations/User"
}
}
],
"responses": {
"400": {
"description": "Invalid user supplied"
},
"404": {
"description": "User not found"
}
}
}
}
If you paste your API definition into https://editor.swagger.io, it will flag 2 syntax errors in the PUT operation. Make sure to fix these errors before testing your API.
In the parameter definition, change "name":"Id" to "name":"id" (lowercase id) to match the parameter letter case in the path template.
In the body parameter, change $schema to schema.
I am running into an issue with posting a json doc via request from my nodeJs app.
The problem is for me how to pass the json doc to post. Here is what works for me
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: { "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "</p>\r\n\r\n<ul type=\"disc\">\r\n\t<li><strong>Ready to Use Experiences</strong> – Get instant access to our fully configured and integrated environments allowing you to use and experience the products as a customer would in their own deployment. We’ve set up the products alongside partner solutions so you can experience the entire ecosystem including Office 365, Salesforce, and more. </li>\r\n</ul>"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#ueser.com"
}} ]}}}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
the problem i have is if i want to pass the body from a string like this
var mybody = `{ "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "This is a test"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#user.com"
}
}]}}`
and then call it like this
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: mybody
}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
which throws errors like
SyntaxError: Unexpected token " in JSON at position 0
Have you tried using stringify? Node.js has a a built in module called querystring.
const querystring = require("querystring");
const myStringBody = querystring.stringify(myBody);
Then write it to your request.
req.write(myStringBody);
I have this post request to JIRA to create an issue:
require('isomorphic-fetch');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var summ = "Review Test Ticket";
var issue = {
"fields": {
"project":
{
"key": "ABC"
},
"summary": summ,
"description": "This is a test JIRA issue creation",
"issuetype": {
"name": "Story"
},
"assignee": {
"name": "myname"
},
"customfield_10902": [{ "value": "Red Team" }],
"customfield_10008": 1
}
};
var missue = JSON.stringify(issue)
fetch("https://my_jira_host/jira/rest/api/2/issue/", {
body: missue,
headers: {
"Authorization": "Basic my_auth_token",
"Content-Type": "application/json"
},
method: "POST"
})
.then(function( data ) {
console.log(data);
}).catch(function(data) {
alert(data);
});
If the above code is in a file called "my_file.js" if I run node my_file.js the ticket is successfully created.
However, if I move that code inside a function that runs on button click in my react app, and then run the app (on localhost or a server) then it fails. I get a 403. The alert displayed from my catch is: TypeError: NetworkError when attempting to fetch resource.
I have tried absolutely everything. Have no idea where to go from here. Any ideas?
When I try to create an Issue via the Jira API REST, I get a 500 Internal server error, I succeeded to get an issue from a project with a get-request but when I try the post-request to create a new issue it doesn't work I get the error.
Here is my JavaScript code :
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
data: {
"fields": {
"project": {
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Error content :
{
"body": "{\"errorMessages\":[\"Internal server error\"],\"errors\":{}}",
"headers": "{\"server\":\"nginx/1.6.0\",\"date\":\"Tue, 14 Apr 2015 13:45:38 GMT\",\"content-type\":\"application/json;charset=UTF-8\",\"transfer-encoding\":\"chunked\",\"connection\":\"close\",\"x-arequestid\":\"945x246734x1\",\"set-cookie\":[\"JSESSIONID=838923A79DA31F77BDD62510399065CF; Path=/; HttpOnly\",\"atlassian.xsrf.token=BQIV-TVLW-FGBG-OTYU|63c1b4a7b87a9367fff6185f0101c415f757e85b|lin; Path=/\"],\"x-seraph-loginreason\":\"OK\",\"x-asessionid\":\"ughpoh\",\"x-ausername\":\"alaa\",\"cache-control\":\"no-cache, no-store, no-transform\",\"x-content-type-options\":\"nosniff\"}",
"status": 500
}
Use params instead of data
JS:-
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
params: {
"fields": {
"project": {
"key": "TASC"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Reference
It looks like it's expecting some non-null value when it's trying to parse the project or issuetype fields, though without the full stacktrace, it's hard to be sure.
You might try adding an id property to both the project and issuetype fields:
params: {
"fields": {
"project": {
"key": "TASC",
"id": "10001"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"id": "1",
"name": "Bug"
}
}
}
Obviously you'll want to make sure to use an appropriate value in both cases.