AEM JCR - Get response as JSON - json

We are adding some metadata under a specific location in JCR:
POST /some/jcr/location/_jcr_content/json HTTP/1.1
Accept: application/json
Authorization: Basic YWRtaW46YWRtaW4=
Cache-Control: no-cache
Host: localhost:4502
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------554953211468377919703514
Cookie: cq-authoring-mode=TOUCH
Content-Length: 383
----------------------------554953211468377919703514
Content-Disposition: form-data; name="./value"
{ "test": "test" }
----------------------------554953211468377919703514
Content-Disposition: form-data; name=":cq_csrf_token"
ey***our csrf token***-c5Oa0
----------------------------554953211468377919703514--
But when we fetch this same resource, the response type is test/html`:
GET /some/jcr/location/jcr:content/json/value HTTP/1.1
Accept: application/json
Cache-Control: no-cache
Host: localhost:4502
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: cq-authoring-mode=TOUCH
HTTP/1.1 200 OK
Date: Fri, 26 Feb 2021 13:49:38 GMT
X-Content-Type-Options: nosniff
Content-Type: text/plain;charset=utf-8
Content-Length: 18
{ "test": "test" }
What configuration do we need to add in JCR, or what do we need to edit in our request to make sure that JCR returns content type application/json.
UPDATE: As Sharath Madappa replied, you can request the data in JSON format by suffixing the location with the .json extension. However, that results in the following format:
{
"value": "{ \"test\": \"test\" }"
}
While I expect it to be:
{
"test": "test"
}

use GET /some/jcr/location/jcr:content/json/value.json while making the request. Sling is able to render/return the resource in multiple formats based on the extension in the request. By default, if no extension is provided it goes with HTML. The path tells which resource, the extension, and selectors tell how and what renders the resource.

You can also specify the depth you want to go for besides having JSON format response.
E.g
Depth of 1(just the node) in JSON format:
curl -u <user>:<pass> -v <URL>/some/jcr/location/jcr:content/json/value.1.json
All child nodes under a certain path in JSON format:
curl -u <user>:<pass> -v <URL>/some/jcr/location.-1.json

Posting JSON content and then retrieving it as Content-Type: application/json can be done by file upload instead of adding properties.
Here is a javascript example:
const data = { test: "test" };
const jsonData = new Blob([JSON.stringify(data)], { type: 'application/json' });
const formData = new FormData();
formData.append(`myFile.json`, jsonData, `myFile.json`);
return fetch(path, {
method: 'POST',
body: formData
});
This example does not take in account Authn/Authz.
To fetch you data as application/json, you just issue a GET call to the location of the JSON file:
http://localhost:4502/path/to/the/folder/jcr:content/files/myFile.json

Related

Ajax request returns bad request error code

I am getting a bad request response to my request. I have checked with an online JSON validator my dictionary data to be correct, and everything seems fine.
My code is the following:
// Parse datetime to timestamp and include data in a dict
let data_dict = {
"stop_date": Date.parse(sup_limit.value),
"start_date": Date.parse(inf_limit.value)
}
// Send the Ajax request
let request = $.ajax({
url: url,
type: 'POST',
data: data_dict,
contentType: 'application/json;charset=UTF-8',
});
Backend receive endpoint:
#dashboard_bp.route('/download_last_test_influx<mode>', methods=['GET', 'POST'])
#login_required
def download_last_test_influx(mode: str):
# Check if request comes from a custom or test event
if mode == 'custom':
start_date = int(request.json.get('start_date'))
stop_date = int(request.json.get('stop_date'))
# Check if time range is valid, if not return server internal error
if stop_date - start_date <= 0:
return jsonify({'message': 'Time range must be grater than 0'}), 500
# Create response header
response = make_response(send_file(spock_comm_mgr
.test_backup_influx_manager
.get_last_test_influx_record(start_date=start_date, stop_date=stop_date)))
response.headers['Content-Type'] = 'application/gzip'
response.headers['Content-Encoding'] = 'gzip'
return response
Request header:
POST /download_last_test_influxcustom HTTP/1.1
Host: 0.0.0.0:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json;charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 48
Origin: http://0.0.0.0:5000
Connection: keep-alive
Referer: http://0.0.0.0:5000/influx_management
Cookie: *********************
Request payload:
stop_date=1623758400000&start_date=1623708000000
Response message:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
You are telling your server, you are sending JSON data, but the request body is not a JSON string but a url-encoded string (because that's the default behaviour of $.ajax() when you pass an object as data).
Use JSON.stringify, to pass a correct JSON body
let request = $.ajax({
url: url,
type: 'POST',
data: JSON.stringify(data_dict),
contentType: 'application/json;charset=UTF-8',
});

How to read json data of a bad request (status code 400) using Alamofire

I was calling a Rest API locally from terminal. This was like below:
http -v -f --timeout=60 GET 'http://localhost:8080/api/v1/public/users/signin?email=myemail#email.com&password=mypassword'
It is returning following output:
GET /api/v1/public/users/signin?email=myemail#email.com&password=mypassword HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8080
User-Agent: HTTPie/0.8.0
HTTP/1.1 400 Bad Request
Content-Type: application/json
Date: Mon, 28 Mar 2016 16:59:08 GMT
Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Sun, 27- Mar-2016 16:59:13 GMT
Transfer-Encoding: chunked
{
"debugMessage": "Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - najmul#qianalysis.com, rememberMe=true] did not match the expected credentials.Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - najmul#qianalysis.com, rememberMe=true] did not match the expected credentials.: The subject was expected to be true, but was false",
"errorCode": "INCORRECT_CREDENTIALS",
"logId": "50a695c1a81e0542",
"stackTrace": "org.niopack.r.....
}
Now I want to read this JSON data using Alamofire. I tried with responseJSON serialiser with following way:
Alamofire.request(method, urlString, parameters: parameters, encoding: .URL, headers: cookieHeader)
.validate()
.responseJSON {
alamofireResponse in
let jsonData = alamofireResponse.result.value
}
But this I am getting jsonData as nil. What you will do if you were are here?
Thanks.
For me removing the validate() allowed me to see the reason the request was failing. For some reason when validate fails, the data of the response is not parsed.

mongolab's REST API auto increment field in mongodb

I want to insert new record with incrementing counter field using REST api provided by mongolab.com
Ex:
Post-method REST call 1:
POST /api/1/databases/thedatabase/collections/Member?apiKey=xXxxxxXXXxxxxXXXxxxxXXXXxxxXXXXxxX HTTP/1.1
Host: api.mongolab.com
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 4c66f955-758a-81e4-484e-89408d643eba
{
"name":"Jack"
}
Post-method REST call 2:
POST /api/1/databases/thedatabase/collections/Member?apiKey=xXxxxxXXXxxxxXXXxxxxXXXXxxxXXXXxxX HTTP/1.1
Host: api.mongolab.com
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 4c66f955-758a-81e4-484e-89408d643eba
{
"name":"John"
}
I want this to effect as { "_id": 1, "name":"Jack" } , { "_id":2, "name":"John" }
Tried using $inc operator, getNextSequence() methods but not working for mongolab.com's REST API.
Anybody with solution?

HTTP 500 when trying to upload a file

Here is my Box upload POST to upload a file into a specific folder:
POST /api/2.0/files/content HTTP/1.1
Authorization: Bearer ACCESS_TOKEN
Accept: application/json
User-Agent: SOASoftware/7-HttpCore/4
Transfer-Encoding: chunked
Content-Type: multipart/form-data
Host: upload.box.com
Connection: Keep-Alive
attributes='{"name":"lead.txt", "parent":{"id":"2890481033"}}'&file=C:\SOA\Software\sm70\instances\nd\leads.txt
-----------------------------9051914041544843365972754266
<file-data>
-----------------------------9051914041544843365972754266
but I get this response, that doesn't help me to understand what the problem is:
HTTP/1.1 500
Age: 0
Date: Fri, 02 Jan 2015 09:06:09 GMT
Connection: close
EMPTY MESSAGE
Can anyone tell me what I'm doing wrong in my request to cause the HTTP 500, please?
It looks like your multipart request isn't properly formatted. The easiest way to do this is to use an SDK or find a library that can build a multipart request for you.
If you really want to build the request manually, then here's an example of what an upload request should look like:
POST https://upload.box.com/api/2.0/files/content HTTP/1.1
Host: upload.box.com
Authorization: Bearer ACCESS_TOKEN
Content-Length: 346
Content-Type: multipart/form-data; boundary=------------------------393329c2f2238ab4
--------------------------393329c2f2238ab4
Content-Disposition: form-data; name="attributes"
{"name":"my-file.txt", "parent":{"id":"0"}}
--------------------------393329c2f2238ab4
Content-Disposition: form-data; name="file"; filename="my-file.txt"
Content-Type: application/octet-stream
<file-data>
--------------------------393329c2f2238ab4--

Error creating DocuSign Envelope via DocuSign Rest API (with multiple documents and multiple recipients)

I am trying to create an Envelope in DocuSign with multiple documents using the DocuSign REST API, I'm using a multipart/form-data request, I use JSON to define the attributes of the envelope, I check my JSON and I think it is OK. Below that I define a multipart/mixed section where I set the header and PDF bytes of the documents. I receive a Bad Request error code that said "NO_DOCUMENT_RECEIVED" and have as message "The document element did not contain the encoded document, or there is a problem with the encoding. ". I post the request result from fiddler below:
// Request
POST https://demo.docusign.net/restapi/v2/accounts/295724/envelopes HTTP/1.1
X-DocuSign-Authentication: {"Username":"email","Password":"password","IntegratorKey":"key"}
Content-Type: multipart/form-data; boundary=9a56da749dc04804819460f6499ab80b
Accept: application/json
Host: demo.docusign.net
Content-Length: 31476
Expect: 100-continue
--9a56da749dc04804819460f6499ab80b
Content-Type: application/json
Content-Disposition: form-data
{"emailBlurb":"EMAIL BODY HERE OK OK","emailSubject":"EMAIL SUBJECT HERE IS MANDATORY","status":"sent","documents":[{"documentId":1,"name":"ABC.pdf"},{"documentId":2,"name":"AB.pdf"}],"recipients":{"signers":[{"email":"dn#brenock.com","name":"Dubhe","recipientId":"1","routingOrder":"1"},{"email":"dubhe.dnacimiento#gmail.com","name":"DubheF","recipientId":"2","routingOrder":"1"}]}}
--9a56da749dc04804819460f6499ab80b
Content-Disposition: form-data
Content-Type: multipart/mixed; boundary=e8bc9555e9634110bba63547b2552460
--e8bc9555e9634110bba63547b2552460
Content-Type: application/pdf
Content-Disposition: file; filename=ABC.pdf; documentId=1
<PDF Bytes Document 1>
--e8bc9555e9634110bba63547b2552460
Content-Type: application/pdf
Content-Disposition: file; filename=AB.pdf; documentId=2
<PDF BytesDocument Two>
--e8bc9555e9634110bba63547b2552460--
--9a56da749dc04804819460f6499ab80b--
You shouldn't need these lines that define a second boundary (or any of the subsequent references to that second boundary):
Content-Disposition: form-data
Content-Type: multipart/mixed; boundary=e8bc9555e9634110bba63547b2552460
Try removing that (and all subsequent references to boundary e8bc9555e9634110bba63547b2552460), so that your request looks like this:
POST https://demo.docusign.net/restapi/v2/accounts/295724/envelopes HTTP/1.1
X-DocuSign-Authentication: {"Username":"email","Password":"password","IntegratorKey":"key"}
Content-Type: multipart/form-data; boundary=9a56da749dc04804819460f6499ab80b
Accept: application/json
Host: demo.docusign.net
Content-Length: 31476
Expect: 100-continue
--9a56da749dc04804819460f6499ab80b
Content-Type: application/json
Content-Disposition: form-data
JSON_REQUEST_BODY_HERE
--9a56da749dc04804819460f6499ab80b
Content-Type:application/pdf
Content-Disposition: file; filename="ABC.pdf"; documentid=1
DOCUMENT_1_BYTES_HERE
--9a56da749dc04804819460f6499ab80b
Content-Type:application/pdf
Content-Disposition: file; filename="AB.pdf"; documentid=2
DOCUMENT_2_BYTES_HERE
--9a56da749dc04804819460f6499ab80b--