400 error message when trying to create a new document in CouchDb using XMLHttpRequest - xmlhttprequest

I am trying to create a new document in a couchDB database but with the following code I get a '400 bad request' response. I want to create a document that does not contain any other information than the _id (and of course the generated _rev).
var xhrCreate = new XMLHttpRequest();
xhrCreate.open('PUT','http://domainName:5984/dbName/docName/', true);
xhrCreate.setRequestHeader("Content-type", "application/json");
xhrCreate.send();
The CouchDb documentation says that a 400 error indicates a:
"Bad request structure. The error can indicate an error with the request URL, path or headers. Differences in the supplied MD5 hash and content also trigger this error, as this may indicate message corruption."
Could anyone point me in the right direction? Hints and help is much appreciated.

CouchDB requires an empty document as part of the content:
xhrCreate.send('{}');

Related

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

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.

Google Sheet API batchUpdateByDataFilter PHP Function

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdateByDataFilter
We have used above function in our code, while we are passing the more than 50 or 100 records within the array records then given 400 bad request array in response.
Can anyone describe the limit of the total values that we are going to pass within the above function?
Here is my code:
$batchupdate = array("valueInputOption" => "RAW", "data" => $dataarray);
try {
$requestBody = new Google_Service_Sheets_BatchUpdateValuesByDataFilterRequest($batchupdate);
$response = $service->spreadsheets_values->BatchUpdateByDataFilter($spreadsheetId, $requestBody);
}
catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}
Troubleshooting:
Problems with the Request
Until you attach a sanitized version of your Request body we cannot be sure about the root-cause of the problem you are facing.
However, an error 400 means that the request you did is invalid. So, most likely, the problem is in that.
Check if your request object is formatted as detailed on the documentation.
Problems with the Client
If you are able to use the Try this API sidebar with the same Request Body then it could be related to the PHP client.
Note: This is language independent. Create a JSON Object that has the same structure as your request body.
If that's the case, we will need to see more of your code to verify that you are not using your valid Request body in an invalid way (eg. sending it encapsulated in another object).
By referencing the PHP Library documentation you can see the properties of the objects you can use.

Invalid Session ID from SalesForce REST API

I'm making a call to the SalesForce REST Api.
However, I have a very weird error. Initially I wrote this in a VB.NET Module file. Everything was working correctly, as soon as I put the method in a class I keep getting the darn Invalid Session ID error. The error doesn't seem to suggest which part of the code is failing.
I am using RestSharp to facilitate the call to the SalesForce API, and I know for a fact it works because in the Module file I am able to fetch the data that I need.
I do not understand the rationale about why it works in the Module file but not in a class file.
Anyways, here is the code that I've placed in both the class file and the Module file to facilitate the call:
client = New RestClient(_strURI)
request = New RestRequest(Method.POST)
request.AddParameter("grant_type", "password")
request.AddParameter("client_id", _strClientID)
request.AddParameter("client_secret", _strClientSecret)
request.AddParameter("redirect_uri", _strRedirectUrl)
request.AddParameter("username", _strUserName)
request.AddParameter("password", _strPassword & _strSecurityToken)
'Dim response As IRestResponse
Dim response As IRestResponse = Nothing
response = client.Execute(request)
'This is the offending line in the class file..it returns back a HTTP 200 yet gives me that Session Invalid error
If response.StatusCode <> HttpStatusCode.BadRequest Then
token = JsonConvert.DeserializeObject(Of TokenResponse)(response.Content)
Dim listViewResults As String = HttpGet(token.instance_url & "/services/data/v38.0/sobjects/Contact/listviews", "")
I am unsure whether this is a permission issue or more of a programming error; because in both cases all of the authentication strings are the same. At the moment I've hardcoded it to point to a test profile. So I can't pinpoint what exactly I am doing wrong?
Any help would suffice.
Stupid me,
Anyways shortly after I posted this I went and took a brisk walk outside of the office. Turned out to be a misnomer.
I had the same HttpGet method defined in the module file and forgot to copy and paste that into the class file. When I actually stepped through it, it threw an Exception inside.
Turned out the only fix needed was to put that method into the class file.

Outpan API C# POST Request

What does the Outpan server expect when posting data?
GET was giving me a json info that I was able to convert to an object.
Now when I'm giving information back just like the name:
https://api.outpan.com/v2/products/UPCCode/name?apikey=xxx
it will always not understand my information (error 400). Already tried sending the json back with additional info, "Foodname" and "name = Foodname"

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