How to send form-data with RestClient, if data received from a hash? - ruby

I have an API endpoint that requires data to be sent to it as form-data. I am using RestClient for sending the data. The problem is that I do not manage to give the data for the request in a way, that the endpoint would be able to read it. This is what I have tried:
RestClient::Request.execute(
method: :post,
url: url,
payload: {
multipart: true,
data: {
"user": "test",
"phase": "test",
"job_id": "test"
}
},
headers: { Authorization: 'Basic ' + Base64.encode64(auth_details), content_type: "multipart/form-data"}
)
Any advices how I could add the hash-data for the request in a way that the endpoint could read it as a form?
EDIT1:
The endpoint does receive the request. The endpoint is written with Flask and it tries to read the form parameters using flask.request in the following way:
request.form.get("user")

I managed to get the request working by changing the reuquest to be the following:
RestClient::Request.execute(
method: :post,
url: url,
payload: {
"user": "test",
"phase": "test",
"job_id": "test"
},
headers: { Authorization: 'Basic ' + Base64.encode64(auth_details),
content_type: "multipart/form-data"}
)

Related

Cypress: Should new cy.intercept() method mock responses for requests sent not from browser, but using cy.request() method?

I am creating an end to end test, where some specific data should be retrieved via API using
cy.request({
method: "POST",
url: ...,
headers: {
"X-Auth-Token": ...,
},
body: {
target_url: ...,
},
});
For now my API can't send me the data, so while it is being fixed I had an idea to mock this request using
cy.intercept(
{
method: "POST",
url: ...,
},
{
body: {
target_url:
...,
},
}
So I can set all necessary data into the body to stub response
But it just does not work for me now, I read carefully all the docs, but still I can't understand - cy.intercept does not work for cy.request or I just made an error somewhere?
Thank you for any information =)

POST call to Intercom API using httparty does not work because the "Query body must contain a query hash"

I want to use httparty to make a POST call to the Intercom API in order to search for conversations following certain criteria.
I tested first in Postman and it works fine (see screenshot on the following link)
API call inside Postman
However, when I want to make this API call in ruby using the httparty gem, it does not work.
I used the following code:
headers: {
"Content-Type": "application/json",
Authorization: "Bearer {{value of the token}}",
Accept: "application/json",
},
query: {
"field": "updated_at",
"operator": ">",
"value": 1592248820
}
}
results = HTTParty.post('https://api.intercom.io/conversations/search', options)
It returns me the following error:
{"type":"error.list","request_id":"0001t1gne3j7pscoq2n0","errors":[{"code":"invalid_query","message":"Query body must contain a query hash"}]}
It is really strange because I tested this syntax for another POST call to the Intercom API using exactly the same syntax and it worked fine. See below:
headers: {
"Content-Type": "application/json",
Authorization: "Bearer {{value of the token}}",
Accept: "application/json",
},
query: {
"email": "wash#serenity.io",
"name": "Hoban Washburn",
"role": "user"
}
}
results = HTTParty.post('https://api.intercom.io/contacts', options)
My first thought is that the query has to be in the body of the call, so I'd suggest trying...
headers: {
"Content-Type": "application/json",
Authorization: "Bearer {{value of the token}}",
Accept: "application/json",
},
body: {
query: {
"field": "updated_at",
"operator": ">",
"value": 1592248820
}
}
}
That also matches your Postman call better.

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

how to reproduce successful curl call in ajax

In Charles proxy I've captured a successful request made when using curl - which returns some json. I've tried all day to make this into an ajax call but have failed - wonder if someone could take a fresh look at it? I'm sending a token via the header to a service that provides this json
{
"category": [{
"id": 1,
"name": "aaa",
"description": "anything..."
}, {
"id": 2,
"name": "ccc",
"description": "desc 1111..."
}, {
"id": 3,
"name": "ddd",
"description": "desc..."
}]
}
charles dump of the good request made with curl
GET /api/v1/category HTTP/1.1
User-Agent curl/7.30.0
Host myurl.com
Accept */*
Authorization Token token=6ff1fed470ec2ddaf8b3af9584619902
the raw info
URL http://myurl.com/api/v1/category
Status Complete
Response Code 200 OK
Protocol HTTP/1.1
Method GET
Kept Alive No
Content-Type application/json; charset=utf-8
Client Address /127.0.0.1
Remote Address myurl.com/23.23.121.64
my attempt
$.ajax({
beforeSend: function (xhr) { xhr.setRequestHeader ('Authorization', 'Token 6ff1fed470ec2ddaf8b3af9584619902') },
type: "GET",
url: "http://myurl.com/api/v1/category",
dataType: "json"
}).done(function( msg ) {
console.log( msg );
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log( "Request failed: " + textStatus );
console.log( errorThrown );
});
thanks in advance!
You haven’t posted the diagnostics for your attempt, so I’m just going to guess from your code.
You send
Authorization: Token 6ff1fed470ec2ddaf8b3af9584619902
from XHR, but
Authorization: Token token=6ff1fed470ec2ddaf8b3af9584619902
from curl—note the token=.
You have to make sure that http://myurl.com/api/v1/category either supports cross-origin resource sharing or is located at the same origin (domain) as the page that executes that JavaScript code.
If these do not help, post whatever error messages you get.

Trigger.io Ajax Requests - with Parse Facebook User authentication

I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.
Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});

Resources