using /upload urls with Google API client - gmail-api

Consider this:
I am fetching rawbody messages by this call:
service.users().messages().get(userId='me', format='raw', id=msgid)
Then I am pushing rawbody messages by this Call:
service.users().messages().insert(userId='me', body=message)
Now when the mails contain attachments bigger 5MB, I encounter 413 "Request Entity Too Large.", and I can't push mails.
GMail API messages.insert Documentation advices to use
POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages
instead of
POST https://www.googleapis.com/gmail/v1/users/userId/messages.
But Google API Client doesn't seem to have any documentation about how to call the above Url, and it keeps getting back to latter url.
How Can send post requests to first url(with /upload) with Google Api Client rather than its default?
How to use /upload url and set uploadType=multipart with Google APi Client?

Yeah, this was totally unclear from the documentation for the Google Python API client, but I found the solution in this other answer. It turns out that you use the same method (users().messages().insert()) but you pass media_body instead of body['raw']. Something like this should work:
from io import BytesIO
from base64 import urlsafe_b64decode
import googleapiclient.http
b = BytesIO()
message_bytes = urlsafe_b64decode(fetched_message['raw'])
b.write(message_bytes)
media_body = googleapiclient.http.MediaIoBaseUpload(b, mimetype='message/rfc822')
service.users().messages().insert(userId='me', media_body=media_body).execute()
I haven't tried using uploadType=multipart, but maybe you can figure it out from this documentation page and looking at the contents of the googleapiclient.http module.

Related

REST API endpoint returns no response with axios in react, but works fine in browser

I created a simple REST API with express and bodyParser which returns a json object on a GET request to the base url. Works fine in the browser and returns what's expected:
API Endpoint: https://jk9j0.sse.codesandbox.io/.
Code: https://codesandbox.io/s/magical-montalcini-jk9j0
Then I setup a basic react app to consume this API by sending a GET request with axios. But on calling the API endpoint above, I get no response. Trying to catch the error.request object, I don't see anything that's clearly incorrect in the headers. The error object itself says 'Network Error'. Not sure why, when the API works as expected in a browser.
Note: When I replace my API url with another one, which is expected to send a similar response, things work great.
The one that works: https://jsonplaceholder.typicode.com/posts/
I haven't created that one, but used it to model my json object.
React Code: https://codesandbox.io/s/hungry-sun-rq94r
I've tried investigating from several angles but no luck. What am I missing here? Do I need to set some headers in the request? Is this a CORS issue?
Yes, it turned out to be a CORS issue. Had to apply header in the API end-point before sending response. res.header("Access-Control-Allow-Origin", "*").

App Engine different response on browser vs postman

I have a nodejs express server running on app engine.
If i make a GET request to https://astral-pursuit-252600.appspot.com/users in the browser it works fine to say unauthorized (401).
If I do the same GET request in postman it returns 400 bad request.
Is there any obvious reason why this is occurring?
This is a known issue with postman. This tool sends certain headers by default that you cannot remove. App Engine does not like them for some reason. I had to use the Insomnia tool instead which does not include default headers.
The first thing that I can think about is that, in order to do an API call, you need to use an API key in your request. You should create one, after that you need to obtain an access token. Your requests should be send to an address like https://astral-pursuit-252600.appspot.com/users?key=YOUR_API_KEY and include in your request a header to contain the access token. Something like this : --header 'authorization: Bearer YOUR_ACCESS_TOKEN'.
In order to do that I do not think you need to change manually each request, but you need to change some POSTMAN settings. You can find here a guide with exactly what setting should be changed for this use case.
You can see more details about this topic and a more detailed guide for doing an API calls here.
In case this was not the issue, could you please provide me your POSTMAN settings? I am pretty sure this is about the way POSTMAN does the requests anyway.

Google API Request stopped working

I have an API that I use to get the events from multiple accounts. Recently the API stopped working and I am not able to figure out why.
Here is an example of my request: https://www.googleapis.com/calendar/v3/calendars/pub500.mankato%40gmail.com/events?key=myKey
The call returns a Google_Service_Exception - (400) Bad Request
From you question, I take it that you are managing authentication for calling APIs. Based on the information provided by Michael, I think you will find this GCP documentation for using API keys helpful:
https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
The answer to this question (is|was) to validate the error response message from the API and read it carefully. I also recommend rechecking API settings(Console), the API call and to check every single step if its use in any kind of framework. (Test against the API)
Google_Service_Exception - (400) Bad Request
seems to be invalid API credentials (API key)
Update after creating new API key:
"(403) The request did not specify any referer.
Please ensure that the client is sending referer
or use the API Console to remove the referer restrictions."
That means you have to specify a referer in your API call or go to your API console (where you created the new KEY) and remove the "referer restriction"

How to send POST login request to a rails api-only app using React?

I have a working rails RESTful api-only app.
I use Postman to consume that api. Now, to use the api the user have to login to http://localhost:3002/authenticate first by setting content-type to application-json in Header then Email and Password's value in body. After sending the POST request to the server I get auth-token as a json response. Then after successful login I have to pass that auth-token as a Authorization key in each GET request to get respective data.
Now, I want to build a UI for that back-end api as I learn React js. But till now all tutorials I could find was how to send GET requests without any authorization factor. And they are using axios, redux etc.
Can any-one please guide me on where should I start or how to
approach this problem?
Do I necessarily have to use a third-party library for this purpose?
If so which will be better axios or redux??
Any beginner friendly tutorial link would be of tremendous help
How start
Securing React Redux Apps With JWT Tokens - Rajaraodv explains how you get a jwt token and how to keep it in the front end app. I think this way will fits for you.
Keep the auth-token
Rajaraodv uses localStorage to keep the jwt token, you can use the same or keep directly in redux store, it's your choice, the best manner that fits you.
Ajax call
You can use Axios to make Ajax calls, or use fetchApi from the browser as Rajaraodv did, it's up to you.
Explains
"If so which will be better axios or redux??" these two libraries are totally different, each with it's own purpose.

Open Graph Action POST fails when called thru a google app engine based unpaid instance

urlopen fails with a 500 code and '{"error_code":1,"error_msg":"An unknown error occurred"}' error from Facebook when posting an Open Graph Action. I can get the code to work with other posts (e.g. posting a comment on a status using the graph API works fine). I can also get this action-post to work using curl. So this seems like a urllib2.urlopen issue when posting a form-data with a URL as one of the values.
Graph api post that works with curl :
curl -F 'access_token=nnnnnn' -F 'object=https://abc.com/123' \
'https://graph.facebook.com/me/namespace:action' -k
Same Graph api post thru urllib2 which gives the error :
from urllib2 import urlopen, Request, URLError
request = Request (url='http://graph.facebook.com/me/namespace:action';,
data = urllib.urlencode(
{'object':'https://abc.com/123',
'access_token':'nnnnnnnn'
},
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
)
response = urlopen (request)
What could I be doing wrong ? (I am new to urllib2.urlopen. Btw, I originally tried urlfetch.fetch thru the urlfetch python module. That did not work either). I am using this thru goole app engine.
After a fair amount of digging/trial-error, finally managed to solve this.
This is not an issue with urllib urlopen, but more of a Google App Engine nuance where when an action post on an open Graph URL is called - it causes Facebook to trigger a 'get' on the Object URL (synchronously).
So essentially the get is being called on app engine app while an active instance is already calling the FB graph URL. I am currently using an unpaid instance and this is causing an unexpected behavior such that FB to fails the OG post (I see the get on the logs going thru successfully, while the active post, so not sure what causes FB to fail - anybody with an insight, please share).
I got around this by 'taskqueue'ing urlopen/OG-action-post - and when this is called the second time (FB apparently caches the object the first time) it succeeds.
If anybody needs more details, get in touch and am more than happy to save you all the time and pain that I have already gone thru..

Resources