Unable to get resonse from import contacts sendgrid API using python - sendgrid

Below is the call I am trying to make -
I used field mapping in below data -
data = {
"file_type": "csv",
"field_mappings": [
"_rf2_T",
"_rf0_T",
"_rf1_T",
"_rf10_T",
"w1_T",
"w45_T",
"w46_T",
"w44_T",
"w2_D",
"w43_T"
]
}
print("--data---",data)
response = sg.client.marketing.contacts.put(
request_body=data
)
#print("--data---",data)
print(response.status_code)
print(response.body)
print(response.headers)
and getting below error
{'errors': [{'field': 'contacts', 'message': 'at least one contact is required'}]}
I am expecting upload url and header from api call

Related

Item does not have a file (error 500) when uploading a PNG file to a portal using add item method

I am trying to setup a POST request method using the "Add Item" operation within a REST API for my portal so that the PNG images can be add and later updated. Currently my script uploads the item to the portal but when i try to download the file or share it then it opens a page saying "Item does not have a file . Error 500" I assume its something to do with how i am building the POST request. How should i send the file over the POST request so that i can later download and update the file . Here is my current code:
def add_item(username,files,type,title):
"""
Add an item to the portal
Input:
- file: path of the the file to be uploaded
- username: username of user uploads the item
Return:
- Flag with a list of messages
"""
# set request header authorization type
header = {
'Authorization': f'Bearer {token}'
}
# build url
u_rl = f"{portal}/sharing/rest/content/users/{username}/addItem"
# search for id
req = requests.post(url=u_rl, headers=header,files=files,data={ "type":type,"title":title,"f": "json"})
response = json.loads(req.text)
if 'error' in response.keys():
error = response["error"]
raise Exception(
f"Error message: {error['message']}", f"More details: {','.join(error['details'])}")
return response["success"] if 'success' in response.keys() else False
if __name__ == "__main__":
user = input("input your USERNAME: ")
password = getpass.getpass("input your PASSWORD: ")
portal = "https://cvc.portal"
token = generate_token(user, password, portal=portal)
files = {'upload_file': open(r'C:\Users\test.png','rb')}
type='Image',
title='An image'
add_item(user,files,type,title

Uber Eats API - Fail to collect reports (Could not parse json: readObjectStart: expect { or n, but..)

We are facing an error when we are trying to request UberEats API to collect report about our restaurants based on the Ubereats documentation here.
The error :
'{"error":"Could not parse json: readObjectStart: expect { or n, but found \x00, error found in #0 byte of ...||..., bigger context ...||..."}'
We tried to run the query in python and postman and still facing the same error.
Need help to understand where we failed.
Here the python code run in VSC
import requests
import json
payload = {
"report_type": "FINANCE_SUMMARY_REPORT",
"store_uuids": "xxx",
"start_date": "2022-09-01",
"end_date": "2022-09-15"
}
headers = {
"authorization": "Bearer xxx"
}
report_response = requests.post('https://api.uber.com/v1/eats/report', data=payload, headers=headers)
report_response.text
'{"error":"Could not parse json: readObjectStart: expect { or n, but found \x00, error found in #0 byte of ...||..., bigger context ...||..."}'
Best regards,
You have to convert the payload to valid JSON string and send the request.
headers = {
"Authorization" : "*********",
"Content-Type" : "application/json"
}
import json
response = requests.post("https://api.uber.co/v1/eats/report", data = json.dumps(payload), headers=headers)

How to access custom header from AWS Lambda Authorizer?

I have created an Authorizer in AWS API Gateway. This Authorizer refers to a Lambda Function.
I am passing the following values in header, to the API Endpoint using Postman.
{
"type":"TOKEN",
"authorizationToken": "testing2",
"methodArn": "arn:aws:execute-api:us-west-2:444456789012:ymy8tbxw7b/*/GET/"
}
The above header values are received in the Lambda Function. I can see this through the logs in CloudWatch.
I want to pass additional value 'clientID' in the header. So I pass the following values in the header from postman.
{
"type":"TOKEN",
"authorizationToken": "testing2",
"methodArn": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/GET/",
"clientID" : "1000"
}
In this case, the Lambda function does not get the clientID. I checked various threads in SO, and understood that this can be achieved mapping header. So I did the following.
In the "Method Execution" section of the API method, I created a new header clientID. In the "Integration Request" section, under "HTTP Headers" section I provided the following value
Name: clientID
Mapped from: method.request.header.clientID
After doing the above, I deployed the API and tried to call the method from Postman, but the clientID is shown undefined. Following is the code that I have written in Lambda Function
exports.handler = function(event, context, callback) {
var clientid = event.clientID;
//I always get event.clientID undefined
console.log("The client ID is:" + event.clientID);
}
EDIT
Following is the error from the CloudWatch Log.
START RequestId: 274c6574-dea5-4009-b777-a929f84b9a9d Version: $LATEST
2019-09-19T09:40:25.944Z 274c6574-dea5-4009-b777-a929f84b9a9d INFO The client ID is:undefined
2019-09-19T09:40:25.968Z 274c6574-dea5-4009-b777-a929f84b9a9d ERROR Invoke Error
{
"errorType": "Error",
"errorMessage": "Unauthorized",
"stack": [
"Error: Unauthorized",
" at _homogeneousError (/var/runtime/CallbackContext.js:13:12)",
" at postError (/var/runtime/CallbackContext.js:30:51)",
" at callback (/var/runtime/CallbackContext.js:42:7)",
" at /var/runtime/CallbackContext.js:105:16",
" at Runtime.exports.handler (/var/task/index.js:40:4)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
I have understood why I was not getting the value in the header. I have done the following
1) Instead of type TOKEN, I used type REQUEST in the header. I understood this by reading the following link. This link also contains code for Request type.
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
2) I removed all the mapping from Method Request and Integration Request.
3) Deployed the API.

django-rest-framework: How do I create a Feedback / Contact form without a model?

first-time poster. I’m trying to create a simple contact option using Django Rest Framework. The contact page would allow users and non-users to send the site admin an email via a form. Been at this for weeks… I’ve added my questions and code below.
1) Is it the viewset that needs some additional work to connect to the form data?
2) Does the DRF API viewer allow for testing this out? Should it be showing the email fields?
# serializers.py
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
message = serializers.CharField()
name = serializers.CharField()
# views.py
class CommentViewSet(viewsets.ViewSet):
def list(self, request): #, format=None
comment = CommentSerializer(data=request.data)
if comment.is_valid():
form_email = comment.data['email']
form_message = comment.data['message'] + "email: " + form_email
form_name = comment.data['name']
send_mail("New contact form submission",
form_message,
form_email,
['myemailaddress#gmail.com'],
fail_silently=False
)
return Response(comment.data)
# Not sure how the html connects here:
# return render('comment.html', {
# 'form': form_class,
# })
return Response(
{
"success": False,
'error-code':'invalid-data'
},
)
# urls.py
router = DefaultRouter()
router.register(r'profiles', views.ProfileViewSet)
router.register(r'users', views.UserViewSet)
router.register(r'comment', views.CommentViewSet, 'Comment')
urlpatterns = [
url(r'^', include(router.urls)),
]

Backend Error (HttpError 500) on Google Search Console API calls (webmasters/v3)

I prepared code that should fetch data from google webmaster console new Web API (v3).
import os
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from apiclient.discovery import build
import googleapiclient
import json
client_email = '<ACCOUNT_IDENTIFIER>#<PROJECT_IDENTIFIER>.iam.gserviceaccount.com'
scopes = ['https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters']
private_key_path = os.getcwd() + os.path.normpath('/key.p12')
http = httplib2.Http()
credentials = ServiceAccountCredentials.from_p12_keyfile(client_email,
private_key_path,
private_key_password="notasecret",
scopes=scopes
)
http_auth = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', credentials=credentials, http=http_auth)
query_params = {"startDate": "2016-03-01", "endDate": "2016-03-02"}
try:
quered_results = webmasters_service.searchanalytics().query(
key="<KEY>",
siteUrl="http://<SITE_DOMAIN>/",
body=json.dumps(query_params),
fields="rows",
alt="json"
).execute()
print(quered_results)
except googleapiclient.errors.HttpError as e:
print(e)
Execution results with error:
<HttpError 500 when requesting https://www.googleapis.com/webmasters/v3/sites/http%3A%2F%2F<SITE_DOMAIN>%2F/searchAnalytics/query?key=<KEY>&alt=json&fields=rows returned "Backend Error"
The code from above is for authorization with ssh key with p12 format. Key file is correct. Using client_secrets.json end up with the same error, code. The json for error is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error",
}
],
"code": 500,
"message": "Backend Error"
}
}
I did connect email to webmaster tools console.
Authorization seems to work since there is no errors for used key/account
Any ideas?
I've noticed that the same error occures when I fetch on https://developers.google.com/apis-explorer with "Request body" improperly set, but I do not see error in JSON I send. BTW It would be nice to have some validation message about that...
Found it! body parameter should actually by python object, not JSON formatted string!
body=json.dumps(query_params),
Should be
body=query_params,