I try to get a proper response from the Google Safe Browsing API v4. Although I get the error "Invalid JSON payload received. Unknown name".
I have used a payload based on the payload example mentioned at https://developers.google.com/safe-browsing/v4/lookup-api
I have problems with the payload. I think it should be a string, not a real dict. When I use a dict I get the error: TypeError: has type , but expected one of: str, unicode
The code I used is:
result = urlfetch.fetch(url, method=urlfetch.POST, payload=payload)
The url is (with [api-key] is of course my api-key):
https://safebrowsing.googleapis.com/v4/threatMatches:find?key=[api-key]
The payload is the following string (not a python dict):
{
"client": {
"clientId": "myproject",
"clientVersion": "42" },
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["WINDOWS"],
"threatEntryTypes": ["URL"],
"threatEntries": [ {"url":"http://www.example.com/"} ] }
}
As output I expected some JSON which indicates that this url is safe. However I get the following result:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\n \"client\": {\n \"clientId\": \"myproject\",\n \"clientVersion\": \"42\"\n },\n \"threatInfo\": {\n \"threatTypes\": [\"MALWARE\", \"SOCIAL_ENGINEERING\"],\n \"platformTypes\": [\"WINDOWS\"],\n \"threatEntryTypes\": [\"URL\"],\n \"threatEntries\": [\n {\"url\":\"http://www.example.com/\"}\n ]\n }\n }\": Cannot bind query parameter. Field '{\n \"client\": {\n \"clientId\": \"myproject\",\n \"clientVersion\": \"42\"\n },\n \"threatInfo\": {\n \"threatTypes\": [\"MALWARE\", \"SOCIAL_ENGINEERING\"],\n \"platformTypes\": [\"WINDOWS\"],\n \"threatEntryTypes\": [\"URL\"],\n \"threatEntries\": [\n {\"url\":\"http://www' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": [similar as the message above]
}
]
}
]
}
}
Any ideas, what is wrong?
Thanks
The urlfetch should contain the HEADER Content-Type: application/json
result = urlfetch.fetch(url, method=urlfetch.POST, payload=payload, headers={'Content-Type': 'application/json'})
Related
This is not an authentication error, write is enabled on the database rules.
My cloud Firestore database looks like the picture below.
There is a COLLECTION called colA, inside it there is a DOCUMENT called docA, and inside it there are some fields (strings) stored.
On Postman, if I do GET https://firestore.googleapis.com/v1/projects/eletronica-ab6b1/databases/(default)/documents/colA/docA, I do receive the following answer, and it is correct:
{
"name": "projects/eletronica-ab6b1/databases/(default)/documents/colA/docA",
"fields": {
"fieldB": {
"stringValue": "ABCD"
},
"fieldA": {
"stringValue": "888"
}
},
"createTime": "2020-01-31T16:48:26.859181Z",
"updateTime": "2020-02-05T19:21:49.654340Z"
}
Now, when I try to write a new field (fieldC) via POST https://firestore.googleapis.com/v1/projects/eletronica-ab6b1/databases/(default)/documents/colA/docA, with JSON content:
{
"name": "projects/eletronica-ab6b1/databases/(default)/documents/colA/docA",
"fields": {
"fieldC": {
"stringValue": "1000"
}
}
}
After SEND, I receive this:
{
"error": {
"code": 400,
"message": "Document parent name \"projects/eletronica-ab6b1/databases/(default)/documents/colA\" lacks \"/\" at index 60.",
"status": "INVALID_ARGUMENT"
}
}
What I'm doing wrong? I really would like to write strings there via REST API.
Regards.
Updating a document is done with a PATCH request, according to the [reference documentation).
A POST request is used to create a new document in a collection, which probably explains the error you get: you're pointing to a document, but POST expects a collection path.
I am having issues with the label delete Gmail API.
No matter what label I submit, I get the error response:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidArgument",
"message": "Invalid delete request"
}
],
"code": 400,
"message": "Invalid delete request"
}
}
To reproduce, I first make the request:
POST https://www.googleapis.com/gmail/v1/users/me/labels
{"labelListVisibility":"labelShow","messageListVisibility":"show","name":"C2"}
Which succeeds and then immediately after I send:
DELETE https://www.googleapis.com/gmail/v1/users/me/labels/C2
Which produces the aforementioned error. I can see the label in my gmail inbox so I know it is successfully created and present. Any advice on what I am doing wrong?
You cannot delete a label by name, but must do so by its ID
See here. The Id of the label is contained in the response of the
POST https://www.googleapis.com/gmail/v1/users/me/labels
request:
{
"id": "Label_3",
"name": "C1",
"messageListVisibility": "show",
"labelListVisibility": "labelShow"
}
You can also list all you labels to retrieve their IDs.
The delete request should look something like:
DELETE https://www.googleapis.com/gmail/v1/users/me/labels/Label_3
whereby Label_3 should be replaced by your label ID.
I have mocked my API-Respones with fetchMock (v.5.13.1). I have been working with it for a quite long time now and I didn't see this kind of behaviour yet.
I mocked two GET responses that are very similar.
fetchMock.get('glob:*/shippings/',"results":[
{"id": "1234", "status": "RELEASED", "foo": "bar"},
{"id": "5678", "status": "CREATED", "foo": "bar"},)
fetchMock.get('glob:*/shipping/myId1234',
{"id": "1234", "status": "RELEASED", "foo": "bar"})
Now, the first one works properly, but the second get returns me this error message:
fetch-mock.js:187 Uncaught TypeError: Invalid status RELEASED passed
on response object. To respond with a JSON object that has status as a
property assign the object to body e.g. {"body": {"status:
"registered"}}
I have an assumption, that I cant mock some response that contains a status, because thats in a way a reserved attribute for status codes, but I am not quite sure and I cant find any similar errors online.
For the second request to fetchMock, it assumes status to be one of the standard codes supplied as an integer. According to the docs, the config supplied to fetchMock expects the following params
If an object only contains properties from among those listed below it
is used to configure a Response to return
body: String | Object
Set the Response body. See the non-config Object section of the docs
below for behaviour when passed an Object
Server responded ok { token: 'abcdef' }
status: Integer
Set the Response status
200, 404, 503
headers: Object
Set the Response headers
{'Content-Type': 'text/html'}
redirectUrl: String
The url from which the Response should claim to originate from (to
imitate followed directs). Will also set redirected: true on the
response
throws: Error
Force fetch to return a Promise rejected with the value of throws
new TypeError('Failed to fetch')
However for a custom status attribute you can respond with a body
fetchMock.get('glob:*/shipping/myId1234', {
body: {"id": "1234", "status": "RELEASED", "foo": "bar"}
})
I need some help for access tokens in GCP. I am using Java as program language and I tried different approaches like:
https://cloud.google.com/iap/docs/authentication-howto
and https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth
I am using the second approach. Code snippet:
String privateKeyId = "my-private-key";
long now = System.currentTimeMillis();
String signedJwt = null;
try {
Algorithm algorithm = Algorithm.RSA256(null, privateKey);
signedJwt = JWT.create()
.withKeyId(privateKeyId)
.withIssuer("my-issuer")
.withSubject("my-subject")
.withAudience("https://www.googleapis.com/compute/v1/compute.machineTypes.list")
.withIssuedAt(new Date(now))
.withExpiresAt(new Date(now + 3600 * 1000L))
.sign(algorithm);
} catch (Exception e){
e.printStackTrace();
}
return signedJwt;
Then I perform get instances setting the returned token as Bearer authorization header but response is:
com.google.api.client.http.HttpResponseException: 401 Unauthorized
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
With same credentials I am able to access the SDK.
Thanks!
As per #DalmTo, you should be using the client library for Java. This is the link to get you started.
I am using gmailAPI to read an email message. From the JSON returned, I get an attachmentId and then I query gapi.client.gmail.messages.attachments.get to get the attachment itself. I am testing the code below with a png attachment and I do get JSON back and the data attribute I assume is base64 because that is what the header says
//Yes, I know the code below could be better but for now I am trying to figure what is contained in data.
function getAttachmentContent(attachmentDict, attachmentId, isLast) {
var request = gapi.client.gmail.users.messages.attachments.get({
'userId': 'me',
'messageId': getParameterByName('msgid'),
'id': attachmentId
});
request.execute(function (resp) {
attachmentDict[attachmentId].gmailAttachmentItem.Length = resp.size;
attachmentDict[attachmentId].gmailAttachmentItem.Content = resp.data;
if (isLast) {
//Return only the key values as an array.
var attachmentArray = new Array();
for (key in attachmentDict) {
if(key.indexOf("index") < 0)
attachmentArray.push(attachmentDict[key].gmailAttachmentItem);
}
emailMessage.GmailAttachments = attachmentArray.slice(0, attachmentArray.length - 1);
}
});
}
The JSON fragment which contains the attachmentid
{
"partId": "1",
"mimeType": "image/png",
"filename": "unnamed.png",
"headers": [
{
"name": "Content-Type",
"value": "image/png; name=\"unnamed.png\""
},
{
"name": "Content-Description",
"value": "unnamed.png"
},
{
"name": "Content-Disposition",
"value": "attachment; filename=\"unnamed.png\"; size=13258; creation-date=\"Mon, 29 Aug 2016 13:34:23 GMT\"; modification-date=\"Mon, 29 Aug 2016 13:34:24 GMT\""
},
{
"name": "Content-Transfer-Encoding",
"value": "base64"
}
],
"body": {
"attachmentId": "ANGjdJ8d3DgMc6114J2v-R16nU1biO2et7xOQZuC23BQgIXVq7v8mn-Ssn88I_zD-HOo6ArbKmv7vFe-1mkZKjNVkLPqP1n8wwhCgON-wh_BFkrArBkIU6SWN4Zh2uvKY2FQLIyCcJtyHDmZlgZB8b4MlLGiBXldpLJ0ioTH4f3De9YVuq5AxhioxbS9X2bggN2tT4YOZgXknVpBvsZ0O00Z43jAB92g3xMFqJjYeLN_l-vL0Xb73WY-xtwXWLGAPWlyD0wPq6a4Fi-qX_RWTfwMZN12AtGaLFFyrtGEKSfEo1cLKzYN8VosPPSVZHA",
"size": 18146
}
}
I get this response and the content in data is it base64 image?
I am using jsfiddle link to show the data because pasting the entire response exceeds the 30000 characters limit.
The content in the data attribute is base64 image? If not, what is it? According to Google
attachmentid: When present, contains the ID of an external attachment that can be retrieved in a separate messages.attachments.get request. When not present, the entire content of the message part body is contained in the data field.
size: Total number of bytes in the body of the message part.
data: The body data of a MIME message part. May be empty for MIME container types that have no message body or when the body data is sent as a separate attachment. An attachment ID is present if the body data is contained in a separate attachment.
The size I get back when I download an email message 18146 is different from the attachment size 13258. Attachmentid is present, so I should get the attachment when I use gapi.client.gmail.users.messages.attachments.get but the size is different?
How do I get the image which is attached to the email.
Looks like you're calling with message.get(format=FULL) currently? In that case the "attachmentid" can be supplied to a separate message.attachment.get() call to retrieve the attachment content. You can, alternatively, just call message.get(format=RAW) to retrieve the entire email, unparsed, in a single response.