How to solve HTTPError: 400 Client Error: Bad Request for URL inRobot Frame work - api

I know there are many similar kinds of questions available but none of them worked.
Can someone tell me if there is any kind of syntax error for the Testcase below
Create Token
Create Session testsession ${baseUrl} verify=true
${body}= create dictionary clientId=unittest.cc.client clientSecret=RyDQ$xxxxxRtv
${header}= create dictionary Content-Type=application/json
${resp}= POST On Session testsession ${reqUri} json=${body} headers=${header} params=${ApiKeyParameter}
${source data}= Evaluate json.loads("""${resp.content}""") json
${token}= Set Variable ${source data['accessToken']}
#No errors Uptill this much - Bearer token creation was successful after that getting error while using it
${header}= create dictionary Authorization=${tpre} ${token} Content-Type=application/json cookies=ss-id=KF84fFy4txxxxxxxxx76i; ss-pid=StDTDxxxxxxxxxxxxn7r
${body}= get file API/data.txt
log to console ${header}
${resp}= post on session testsession /orders json=${body} headers=${header}
log to console ${resp.status_code}
The problem is every time I run the test I am getting a 400 error. Below is the Python code provided by POSTMAN and the screenshots of the headers used. Now I am not sure of how to get the HOST header in my python or maybe robot framework.
Please let me know if any additional details are needed. I am not sure of headers in the URL formation while get or post request is done
Is there any way to find that out?
import requests
import JSON
url = "https://domain:10001/orders?format=json"
payload = json.dumps({ Can ignore this part
})
headers = {
'Authorization': 'Bearer xxx',
'Content-Type': 'application/json',
'Cookie': 'ss-id=xxx; ss-pid=xxx'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

If you all ever come across this kind of issue don't forget to check the body of the JSON / XML you are sending.
Mine resolved as I was saving the dump JSON in a text file so while reading from the file my code was adding some extra spaces in front so I was getting a 400 error.
For further information try logging the Response Content it must show you the error message.

Related

API Post request with RobotFramework - Empty Param

I have the following POST request to configure in RobotFramework,
trouble is that the devs set up the request as presented in the screenshot.
This is a file id which you get from a file manager and download it.
My question is since there isn't any params, key, value like FileID etc.
What would be your best bet to send that request successfully via RobotFramework?
[screenshot][1]
The code that I have tried is:
Create Session mysession url=${test_env} verify=true
&{body}= Create Dictionary id=d67b39a6-4ea9-497f-a653-5eb2da418d23
&{header}= Create Dictionary Cache-Control=no-cache
${response}= POST On Session mysession /download data=${body} headers=${headers1}
Status Should Be OK ${response} #Check Status as OK```
Response I receive is Bad Request or Unsupported media
[1]: https://i.stack.imgur.com/kGyHo.png

Karate: Problem with requests using bearer token | Karate is showing "org/apache/commons/codec/binary/Base64" in response instead of HTTP 401 [duplicate]

We're automating our test with karate framework. In one of our features we need to decode a token and get a scope in the response. Everything works well, except this code in js.
function(token) {
return JSON.parse(new Buffer(token.split('.')[1],'base64').toString('ascii')).scope;
}
Error:
Caused by: <eval>:2 ReferenceError: "Buffer" is not defined
Caused by: jdk.nashorn.internal.runtime.ECMAException
In official tutorials it is said that javascript is 'native' to karate, so we don't understand why Buffer is not recognized? What we should do? Thanks for any help
I was able to successfully base64Decode a JWT token payload to JSON using the following code without the need for a Java method:
Background:
* def parseJwt =
"""
function(token) {
var base64Url = token.split('.')[1];
var base64Str = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var Base64 = Java.type('java.util.Base64');
var decoded = Base64.getDecoder().decode(base64Str);
var String = Java.type('java.lang.String')
return new String(decoded)
};
"""
Scenario: JWT Token
Given path 'jwt/authenticate'
And header x-goog-authenticated-user-email = 'email'
And request {}
When method get
Then status 200
* json result = parseJwt(responseHeaders['Set-Cookie'][0])
* match result == {permissions: [1,2,3], iss: "us", exp: "#number", email: "email"}
Note: It does seem to be required to use json rather than def as Karate does better if it parses the string to json itself. Also, you may obtain the token from a header rather than a cookie as in this example if so, just change the responseHeader that you are looking for.
I'm pretty sure that Buffer is advanced / non-standard or NodeJS so it probably is not supported by the JVM JS engine (Nashorn).
Here's my recommendation. For this case, do the work using Java utilities.
For example, look at the Karate basic-auth example in the doc which uses Base64 encoding.
If it is really complex, simply create a Java static function, it will be much easier to test as a side-benefit. Hope this helps !
With respect to the post Karate: Problem with requests using bearer token | Karate is showing "org/apache/commons/codec/binary/Base64" in response instead of HTTP 401
My query was marked duplicate hence posting an answer/solution which we have found in our project.
We did some debugging in karate core about the error. It seemed a dependency was missing.
We added the dependency in the POM.xml
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
Afterwards the problem was resolved and we started getting HTTP 401.
I am not sure it can be added to the karate core.

Variable Path Param for GET request in Jmeter

I'm testing a GET request using Jmeter, this request has path parameter:
rest/V1/autobusca/marketplace/product/:productSku
I'm trying to send the parameter in two different locations
Send Parameters With the Request
And I insert a "User Parameters" as productSku and the value.
I noticed the code response is 200, but the body response is "[]", but when I send it using Postman the response body has a lot of information.
If I change the path in the request like this:
rest/V1/autobusca/marketplace/product/${productSku}
I noticed the code response is 404. Can you help me?
Use "//" instead of "/".
Correct URL will be : rest/V1/autobusca/marketplace/product//${productSku}

ArrayIndexOutOfBoundsException use karate 0.8.0 [duplicate]

I'm trying to upload images on specific slack channel using Karate but no luck, I tried multiple times with different steps but still have 200 response and the image is not displayed in the channel.
Tried to post text content and successfully found the text on the channel.
Bellow are 2 of my tries following the Karate documentation:
#post
Feature: Post images
Background:
* url 'https://slack.com/api/files.upload'
* def req_params= {token: 'xxxxxxx',channels:'team',filename:'from Karate',pretty:'1'}
Scenario: upload image
Given path 'api','files'
And params req_headers
And multipart file myFile = { read: 'thumb.jpg', filename:
'upload-name.jpg', contentType: 'image/jpg' }
And multipart field message = 'image upload test'
And request req_headers
When method post
Then status 200
OR
Given path 'files','binary'
And param req_params
And request read('thumb.jpg')
When method post
Then status 200
Am I missing something? Tried the same examples found in Karate demo GitHub repository of uploading pdf and jpg but no luck.
Note: worked using Slack API UI.
You seem to be mixing up things, there is no need for a request body when you are using multipart. Your headers / params look off. Also based on the doc here, the name of the file-upload field is file. Try this:
Scenario: upload image
Given url 'https://slack.com/api/files.upload'
And multipart file file = { read: 'thumb.jpg', filename:
'upload-name.jpg', contentType: 'image/jpg' }
And multipart field token = 'xxxx-xxxxxxxxx-xxxx'
When method post
Then status 200
If this doesn't work, take the help of someone who can understand how to interpret the Slack API doc. Or get a Postman test working, then you'll easily figure out what you missed.

Upload file to Solr with HttpClient and MultipartEntity

httpclient, httpmime 4.1.3
I am trying to upload a file through http to a remote server with no success.
Here's my code:
HttpPost method;
method = new HttpPost(solrUrl + "/extract");
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
MultipartEntity me = new MultipartEntity();
me.addPart("myfile", new InputStreamBody(doubleInput, contentType, fileId));
method.setEntity(me);
//method.setHeader("Content-Type", "multipart/form-data");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse hr = httpClient.execute(method);
The server is Solr.
This is to replace a working bash script that calls curl like this,
curl http://localhost:8080/solr/update/extract?literal.id=bububu&commit=true -F myfile=#bububu.doc
If I try to set "Content-Type" "multipart/form-data", the receiving part says that there's no boundary (which is true):
HTTP Status 500 - the request was rejected because no multipart boundary was found
If I omit this header setting, the server issues an error description that, as far as I discovered, indicates that the content type was not multipart [2]:
HTTP Status 400. The request sent by the client was syntactically incorrect ([doc=null] missing required field: id).
This is related to [1] but I couldn't determine the answer from it. I was wondering,
I am in the same situation but didn't understand what to do. I was hoping that the MultipartEntity would tell the HttpPost object that it is multipart, form data and have some boundary, and I wouldnt set content type by myself. I didn't quite get how to provide boundaries to the entities - the MultipartEntity doesn't have a method like setBoundary. Or, how to get that randomly generated boundary to specify it in addHeader by myself - no getBoundary methor either...
[1] Problem with setting header "Content-Type" in uploading file with HttpClient4
[2] http://lucene.472066.n3.nabble.com/Updating-the-index-with-a-csv-file-td490013.html
I am suspicious of
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
In the first line, is fileId a string or file pointer (or something else)? I hope it is a string. As for the second line, you can rather set a normal parameter.
I am trying to tackle the HTTP Status 400. I dont know much Java (or is that .Net?)
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error