Gmail Api resumable upload Rest( attachment larger than 5MB) - rest

I am trying to send via Gmail Api Rest a mail with attachment larger than 5MB. To accomplish that I am trying to sent it with resumable upload. This is my code.
byte[] ba = System.IO.File.ReadAllBytes(uploadFromPath);
String base64String = Convert.ToBase64String(ba);
string url = "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=resumable"
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Upload-Content-Type", "message/rfc822");
request.Headers["X-Upload-Content-Length"]= base64String.Length.ToString();
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = body.Length;
After I make the request I am getting the location
location = res.Headers["Location"];
and after that I make the PUT request with the location.
I would like to know what should I insert inside first request Body and what should be inside second request.
I have seen this post Attaching a file using Resumable upload w/ Gmail API
but the code worked only for files smaller than 5MB. Is there anything else I should do to accomplish attchment larger than 5MB?

There's actually samples on the Upload Attachment docs.
Step 1: Start a resumable session
Resumable session initiation request
POST /upload/gmail/v1/users/userId/messages/send?uploadType=resumable HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer your_auth_token
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: message/rfc822
X-Upload-Content-Length: 2000000
{
"id": string,
"threadId": string,
"labelIds": [
string
],
"snippet": string,
"historyId": unsigned long,
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
"body": users.messages.attachments Resource,
"parts": [
(MessagePart)
]
},
"sizeEstimate": integer,
"raw": bytes
}
Step 2: Save the resumable session URI
HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=resumable&upload_id=xa298sd_sdlkj2
Content-Length: 0
Step 3: Upload the file
PUT https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1
Content-Length: 2000000
Content-Type: message/rfc822
bytes 0-1999999

Related

Gatling how to send json body to avoid unmarshal error

I'm trying to send a JSON body to my API using Gatling, but I keep getting error 400 because it cannot unmarshal the body I'm sending:
private val authHeaders = Map(
"Accept" -> "application/json, text/javascript, */*; q=0.01",
"Authorization" -> "Bearer ${access_token}"
)
var requestBody: Body with (Expression[String]) =StringBody("{ \"productId\": " +
product1 + ", \"qty\": "+ 1 +" , \"storeId\": "+ storeId + "}")
var addToCart: ChainBuilder = exec(http("addToCart")
.post(addToCartUrl)
.headers(authHeaders)
.body(requestBody)
.check(bodyString.saveAs("body"))
)
In the Gatling logs I can read that I'm sending this kind of request:
HTTP request:
POST ....
headers:
Accept: application/json, text/javascript, */*; q=0.01
Authorization: Bearer ....
cookie: ROUTE=....
host: .....
content-length: 53
cookies:
ROUTE=...., path=/, secure, HTTPOnly, SameSite=None
body:StringChunksRequestBody{contentType='null', charset=UTF-8, content={ "productId": XXXX, "qty": 1 , "storeId": XXXX}}
I don't think I'm creating the correct body, Is there a way to send only
{ "productId": XXXXX, "qty": 1 , "storeId": XXXXXX} as body?
I might have put the contentType in the wrong way, what is the right order?.
Are you sure product1 and storeId are numbers and not Strings? Otherwise, they must be wrapped with double quotes, which they currently aren't.

perl multipart request using REST::Client

I am using Perl's REST::Client to make a multipart POST request:
#! /usr/bin/perl
use REST::Client;
use JSON;
$file = 'output.csv';
$headers = {'Content-Type' => 'multipart/form-data', 'Authorization' => 'Bearer '.$token.''};
$client = REST::Client->new();
$req = '{"sessionId" => '.$sessionId.' , "content" => ["file" => ['.$file.']]}';
$client->setHost(<host>);
$client->POST( '/api/test',$req, $headers);
$response = from_json($client->responseContent());
REST api is as follow:
#PostMapping("/test")
#Timed
public Response<Map<String, Object>> test(#RequestParam("file") MultipartFile file,
#RequestParam("sessionId") Long sessionId,
HttpServletRequest request) throws URISyntaxException {
}
when I run the script getting following error:
Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found]
I am new with perl, is anything wrong with syntax or something else ?
REST::Client expects you to make the entire message body, and you aren't doing that. Indeed, you shouldn't be trying to do manually construct the request (or even the JSON). I suspect from your code that you aren't really supposed to make a multipart request, but I'd have to see the API docs to say anything about that.
Here's the similar task in Mojo::UserAgent. Instead of trying to make the message body, I make the request with a data structure that Mojo figures out:
use Mojo::UserAgent;
use v5.10;
my $ua = Mojo::UserAgent->new;
my $url ='http://httpbin.org/post';
my $session_id = 'deadbeef';
my $filename = 'upload_file.csv';
my $tx = $ua->post(
$url,
form => {
session => $session_id,
some_file => {
file => $filename,
},
},
);
say "Request:\n", $tx->req->to_string;
say "Response:\n", $tx->result->to_string;
Sending this to httpbin is a convenient way to test things. The output shows that the header and multipart stuff happens for you automatically:
Request:
POST /post HTTP/1.1
User-Agent: Mojolicious (Perl)
Content-Length: 208
Content-Type: multipart/form-data; boundary=75OiX
Accept-Encoding: gzip
Host: httpbin.org
--75OiX
Content-Disposition: form-data; name="session"
deadbeef
--75OiX
Content-Disposition: form-data; name="some_file"; filename="upload_file.csv"
upload,this,file
here's,another,line
--75OiX--
Response:
HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Credentials: true
Date: Sat, 25 Apr 2020 03:44:04 GMT
Access-Control-Allow-Origin: *
Content-Length: 516
Content-Type: application/json
Server: gunicorn/19.9.0
{
"args": {},
"data": "",
"files": {
"some_file": "upload,this,file\nhere's,another,line\n"
},
"form": {
"session": "deadbeef"
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "208",
"Content-Type": "multipart/form-data; boundary=75OiX",
"Host": "httpbin.org",
"User-Agent": "Mojolicious (Perl)",
"X-Amzn-Trace-Id": "Root=1-5ea3b204-12cfdb84b9c9c504da559e80"
},
"json": null,
"origin": "199.170.132.3",
"url": "http://httpbin.org/post"
}
I have many more examples in Mojolicious Web Clients.

Adding document in Couchbase and missing JSON body

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):

What is a correct RESTful service response to a PUT request on successful update?

What is a correct RESTful service response to a PUT request on successful update?
There are two possible responses that seem to comply with REST architectural style:
Return only a header without body with the status 204.
Header:
content-type: application/json; charset=utf-8
status: 204 No Content
ratelimit-limit: 5000
ratelimit-remaining: 4816
ratelimit-reset: 1444931833
Return a header with the status 200 and a body that contains the actual representation of an entity after an update.
Header:
content-type: application/json; charset=utf-8
status: 200 OK
ratelimit-limit: 5000
ratelimit-remaining: 4816
ratelimit-reset: 1444931833
Body:
{
"foo": "bar",
"baz": "qux"
}
If your response includes returned data then its status should be 200, otherwise 204.

While trying to access RedHat BRMS kie server, i am not able to use POST/PUT methods through rest client

Trying to access POST data through rest client, getting 405.
The response headers states Allow: GET, OPTIONS, HEAD.
So how can I make my rest container accept POST/PUT methods?
EndPoint http://localhost:8080/kie-server/services/rest/server Request Headers used -
Content-Type: application/json
authorization: Basic !#$#%&$$(((
Accept: application/json
X-KIE-ContentType: JSON RESPONSE HEADERS
Server: Apache-Coyote/1.1
Allow: GET, OPTIONS, HEAD
Content-Type: text/html;charset=utf-8
Content-Length: 1088
Date: Thu, 01 Sep 2016 08:43:33 GMT
Tried using Advanced rest client,curl and java code but Same results :(
Referred - https://access.redhat.com/documentation/en-US/Red_Hat_JBoss_BRMS/6.3/html/Getting_Started_Guide/chap-Hello_World_rule_example.html
I think you have to change the Endpoint (URL). I would suggest
http://localhost:8080/kie-server/services/rest/server/containers/instances/("nameOfYourDeployment")
Or try without instances.
In Rest Client provide the following set of values:
URL:
http://localhost:8080/kie-server/services/rest/server/containers/instances/<name-of-your-container>
HEADER:
Accept: application/json
Content-Type: application/json
select method type POST and your JSON request payload
When you hit the API it will ask you for the username and password provide the credentials.
fou can send
payload
as:
{
"commands": [
{
"insert": {
"out-identifier": "Input",
"return-object": "true",
"object": {
"<complete-package-name>.<class-name>": {
"variable-1" : "value-1",
"variable-2" : "value-2"
}
}
}
},
{
"fire-all-rules": {
"outIdentifier": "output"
}
}
]
}