Adding document in Couchbase and missing JSON body - rest

I am trying to use Couchbase REST API to add a document to the existing documents. I am just testing this in Postman while writing on the code.
POST:
http://<ip>:8091/pools/default/buckets/<bucketname>/docs/testdoc1?rev=1
Headers:
Accept: application/json
Authorization : xxxxx
Body:
Raw JSON (application/json)
{
"Name": "xxx",
"Address": "yyy",
"Phone number": "xxxx",
"Badge": "yyy",
"BadgeType": "xxx"
}
When I send above in Postman, It is adding this new doc. under couchbase documents/bucket, but on the body field it shows like, "Binary Document, base64 not available"
I tried even from my html code, but json body didn't receive at couchbase end.
<!DOCTYPE html>
<html>
<body>
<input type="submit" value="Start" onclick="submit()">
<script type="text/javascript">
var params = {
"Name": "xxx",
"Address": "yyy",
"Phone number": "xxxx",
"Badge": "yyy",
"BadgeType": "xxx"
}
function submit() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
alert(xhr.response);
}
}
xhr.open('post', 'http://<ip>:8091/pools/default/buckets/<buckname>/docs/testdochtml?rev=1', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + 'xxxxxxx');
xhr.send(JSON.stringify(params));
}
</script>
<p>Click on the submit button.</p>
</body>
</html>
Can someone guide me why is that JSON not going to couchbase in a correct way?

First off: as far as I know, this endpoint is not supported and it is not documented. If you see somewhere that it is supported, let me know, because I think that needs corrected. You should use one of the SDKs (Java, .NET, Node, etc) instead.
That being said, I was able to get it working via Postman. You can't just send raw JSON as the document. You need to POST encoded form data. One of the values this endpoint expects is "value", which contains the encoded JSON document.
Here's an example of what I did (I called my bucket "so"):
POST /pools/default/buckets/so/docs/testdoc2 HTTP/1.1
Host: localhost
cache-control: no-cache
Postman-Token: ba87ef4e-4bba-42b4-84da-ae775b26dbcb
value=%7B%0A%09%22Name%22%3A+%22xxx%22%2C%0A%09%22Address%22%3A+%22yyy%22%2C%0A%09%22Phone+number%22%3A+%22xxxx%22%2C%0A%09%22Badge%22%3A+%22yyy%22%2C%0A%09%22BadgeType%22%3A+%22xxx%22%0A%7D%0A
Note that value above is just the URL-encoded JSON from your question (Postman encoded it for me, and Postman must have added the cache-control header on its own too, because I did not specify that):

Related

How to add API key to Axios post request for mailchimp

I'm trying to set up an axios post request to add members to an audience list, but I can't figure out how to add the API key (keeps giving error 401: 'Your request did not include an API key.'). I've tried a bunch of things in the "Authorization" header, like what I put below (also: "Bearer ${mailchimpKey}", "${mailchimpKey}", "Bearer ${mailchimpKey}", "Basic ${mailchimpKey}", and probably more...).
I also don't know what the "username" would be, but "any" worked when I tested the API elsewhere.
Does anyone know how I should set this up?
axios
.post(
`https://${server}.api.mailchimp.com/3.0/lists/${list_id}/members`,
{
email_address: email,
status: "subscribed",
},
{
"User-Agent": "Request-Promise",
Connection: "keep-alive",
Authorization: `Basic any:${mailchimpKey}`,
// Testing on localhost
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
}
)
If your intention is to use HTTP Basic authentication, just use the Axios auth config option
axios.post(
`https://${server}.api.mailchimp.com/3.0/lists/${encodeURIComponent(list_id)}/members`,
{
email_address: email,
status: "subscribed",
},
{
auth: {
username: "anystring",
password: mailchimpKey
},
headers: { // personally, I wouldn't add any extra headers
"User-agent": "Request-Promise"
}
}
)
HTTP Basic auth headers look like
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
where the string after "Basic" is the Base64 encoded "username:password" string. Axios provides the auth option as a convenience so you don't need to encode the string yourself.
Some other problems you had were:
Adding request headers outside the headers config option
Attempting to send Access-Control-Allow-Origin and Access-Control-Allow-Headers as request headers. These are response headers only. Adding them to your request will most likely cause more CORS errors

How to send Query Params in Get Request in Robot Framework?

I am new to Robot Framework and am facing an issue while sending query params in Get Request method.
Following is the code that I tried with no luck :
Get Data With Filter
[Arguments] ${type} ${filter}
${auth} = Create List ${user_name} ${password}
${params} = Create Dictionary type=${type} filter=${filter}
Create Session testingapi url=${some_host_name} auth=${auth}
${resp} = Get Request testingapi /foo/data params=${params}
Log ${resp}
${type} has value new and ${filter} that I want is id:"1234"
I am expecting final url to formed as :
/foo/data?type=new&filter=id%3A1234
Instead of forming the expected url, I get the request url as :
GET Request using : uri=/foo/data, params={'type': 'new', 'filter': 'id:1234'}
I might be missing something very obvious but I cant figure out what it is. What can I change in this piece of code or any new code that needs to be added?
I think the logger is just outputting the params as the dictionary. The request should actually be made to foo/data?type=new&filter=id%3A1234
You can test it with the following request to Postman Echo (An HTTP testing service):
${auth} = Create List Mark SuperSecret
${params} = Create Dictionary type=Condos filter=2Bedrooms
Create Session testingapi url=http://postman-echo.com auth=${auth}
${resp} = Get Request testingapi /get params=${params}
${json} = To JSON ${resp.content} pretty_print=True
Log \n${json} console=yes
The response will correctly list the params you've encoded:
{
"args": {
"filter": "2Bedrooms",
"type": "Condos"
},
"headers": {
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"authorization": "Basic TWFyazpTdXBlclNlY3JldA==",
"host": "postman-echo.com",
"user-agent": "python-requests/2.25.0",
"x-amzn-trace-id": "Root=1-5fb43ae9-1880b0a621c864b06ce1f54a",
"x-forwarded-port": "80",
"x-forwarded-proto": "http"
},
"url": "http://postman-echo.com/get?type=Condos&filter=2Bedrooms"
}

how to access specific team site in share-point using rest apis

goal: I'm trying to access a specific team site which created in my share-point account using REST APIs and create a folder inside there (Documents folder - default location)
actual results: I'm getting 403 error code. following is the response body which I'm getting.
{
"error": {
"code": "-2147024891, System.UnauthorizedAccessException",
"message": {
"lang": "en-US",
"value": "Access denied. You do not have permission to perform this action or access this resource."
}
}
}
expected result: specified folder should be created and response code should be 201 or 200
what I've tried:
first registered the app in both share-point as well as Azure
get the bearer token calling share-point rest api
tested get apis for share-point and all are worked as expected.
before each request I set the bearer token in the request header
following are the other request headers which I'm setting
Content-Type : application/json;odata=verbose
X-RequestDigest : some random string
Accept : application/json;odata=verbose
following is the share-point REST API, I used POST method for creating a folder
https://***.sharepoint.com/sites/TeamSite_ForB/_api/web/folders
following is the request body which I'm sending
{
"__metadata":{
"type":"SP.Folder"
},
"ServerRelativeUrl":"/Shared Documents/buddhika-test-folder-03"
}
In the share-point documentation site they've provided the API format.
I tried with that format , but couldn't get the result as well.
following is from share-point documentation.
To access a specific site, use the following construction:
http://server/site/_api/web
in that case I have tried as following
https://***.sharepoint.com/TeamSite_ForB/_api/web/folders
I'm getting response as 404 Not found with no response message.
I have searched through many documents but couldn't find how to access a specific team site.
Any help would be appreciated.
The request REST API URL as below.
https://***.sharepoint.com/sites/TeamSite_ForB/_api/web/folders
The request body as following.
{
"__metadata":{
"type":"SP.Folder"
},
"ServerRelativeUrl":"Shared Documents/buddhika-test-folder-03"
}
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getFormDigest() {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" }
});
}
function createFolderTest() {
var documentLibraryName = "Shared Documents";
var folderName="buddhika-test-folder-03";
if(folderName!=""){
createfolder(documentLibraryName,folderName).done(function (data) {
console.log('Folder creted succesfully');
}).fail(function (error) {
console.log(JSON.stringify(error));
});
}
return true;
}
function createfolder(documentLibraryName,folderName){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/folders";
return getFormDigest().then(function (data) {
return $.ajax({
url: requestUri,
type: "POST",
contentType: "application/json;odata=verbose",
data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': documentLibraryName+'/'+folderName}),
headers: {
"accept":"application/json;odata=verbose",
"X-RequestDigest":data.d.GetContextWebInformation.FormDigestValue
}
});
});
}
</script>
<input type="button" onclick="createFolderTest()" value="Create Folder"/>

API request does not authenticate

Using this documentation I'm trying to test the request using Postman the example on the right side:
$ curl https://subscriptions.zoho.com/api/v1/organizations
-H 'Authorization: Zoho-oauthtoken 1000.41d9f2cfbd1b7a8f9e314b7aff7bc2d1.8fcc9810810a216793f385b9dd6e125f'
-H 'X-com-zoho-subscriptions-organizationid: 10234695'
Maybe I'm not setting the parameters right but this is how it looks for the moment.
A new GET Request, in the url input: https://subscriptions.zoho.com/api/v1/organizations
And under that, in the Headers tab I added two key-value pairs:
Authorization: Zoho-oauthtoken 1000.41d9f2cfbd1b7a8f9e314b7aff7bc2d1.8fcc9810810a216793f385b9dd6e125f
Authorization: X-com-zoho-subscriptions-organizationid: 1023469
The returned result:
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
</body>
</html>
If I deleted the second key-value pair it returns this JSON:
{
"code": 57,
"message": "You are not authorized to perform this operation"
}
What is wrong with my approach?
Can you try this?
If you are sure of the api url, do validate the token and create a fresh token and
add it to header as below:
HeaderName : Authorization
HeaderValue: 1000.41d9f2cfbd1b7a8f9e314b7aff7bc2d1.8fcc9810810a216793f385b9dd6e125f
HeaderName : X-com-zoho-subscriptions-organizationid
HeaderValue: 10234695
I tried this and is getting,
{
"code": 14,
"message": "Invalid value passed for authtoken."
}
Might be the token got invalid.
Now I tried with a new token generated myself and I am getting now,
{
"code": 0,
"message": "success",
"organizations": [],
}
In short, you have to generate an auth token first and then hit the url with proper header value as shown above.
Thank you :)

"Resource Not Found" message received when sending a query to Keen IO API

I am using Advanced REST Client tool to test a data pull from the Keen IO API, and think getting the request right, but not getting the data. Getting "resource not found" error. This can also be done via CURL.
Headers: Authorization:
Content-Type: application/json
actual request: GET /3.0/projects//queries/saved/Sponsorships/result HTTP/1.1
HOST: api.keen.io
authorization:
content-type: application/json
Base URL used: https://api.keen.io
Any ideas as to what may be doing wrong?
The saved query name is capitalized "Sponsorships". Make sure your saved query name is lower-cased, not camel or title-cased. To be sure that you are getting the correct saved query name.
Also, you may want to first obtain a list of all saved queries as a reference:
GET /3.0/projects/<project_name>/queries/saved HTTP/1.1
HOST: api.keen.io
authorization: <your_key>
content-type: application/json
You will get something like this:
[
{
"refresh_rate": 0,
"last_modified_date": "2016-12-20T01:09:54.355000+00:00",
"query_name": "",
"created_date": "2016-12-20T01:09:54.355000+00:00",
"query": {
"filters": [],
"latest": 100,
"analysis_type": "extraction",
"timezone": "UTC",
"timeframe": "this_30_days",
"event_collection": ""
},
"metadata": {
"visualization": {
"chart_type": "table"
},
"display_name": ""
},
"run_information": null
}
]
FWIW, I also have seen the "Resource not found" error when writing data to an event if the project is not correctly set up. For example, passing in the wrong project_id or write_key or if the project was deleted from your Keen.io account.