Updating SendGrid contact custom fields via SendGrid API. Why isn't this working? - sendgrid

I'm trying to update my SendGrid contacts and can't figure out why my attempts to update my contacts' custom fields are not working. My reserved fields (first_name, last_name, email) update, but my custom fields do not. Any ideas why?
Documentation here: https://sendgrid.api-docs.io/v3.0/contacts/add-or-update-a-contact
try:
headers = {
'authorization': f"Bearer {settings.SENDGRID_API_KEY}",
}
data = {
"list_ids": [
# "Users" list
"7c2...d20"
],
"contacts": [{
"email": user.email,
"first_name": user.first_name,
"last_name": user.last_name,
"custom_fields": {
"educator_role": user.educator_role,
}
}]
}
response = requests.put("https://api.sendgrid.com/v3/marketing/contacts", headers=headers, data=json.dumps(data))
if(response.status_code != 202):
capture_message(f"Could not add user with email {user.email} to Sendgrid.", level="error")
except:
capture_message(f"Adding/updating SendGrid contact failed for {user.email}.", level="error")```

Unlike reserved fields, updating a custom field requires you pass the custom field id instead of the field name in your call. So instead of educator_role, use the id, it will be something random like e1_T.
You can get the id via the /marketing/field_definitions endpoint.

As said by #Matt, to update a custom field value via SendGrid API, we need to refer to the custom field by its ID, not by the field name.
To get a list with your custom field IDs, do:
from sendgrid import SendGridAPIClient
SENDGRID_API_KEY="print-your-key-here"
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.client.marketing.field_definitions.get()
print(response.body)
Also, take a look at the docs: https://docs.sendgrid.com/api-reference/custom-fields/get-all-field-definitions.
The custom field ID has logic
For custom fields, the unique ID always starts with the suffix e. Followed by an integer number that represents the creation order of the custom fields on the SendGrid platform, p.e. 1, 2, 3. Followed by underscore _. Followed by a letter that represents the custom field type:
N - Number
T - Text
D - Date
Here is an example of a custom field ID list:
{
"custom_fields":[
{"id":"e1_N","name":"number_field_test","field_type":"Number"},
{"id":"e2_T","name":"text_field_test","field_type":"Text"},
{"id":"e3_D","name":"data_field_test","field_type":"Date"}
]
}

Related

Netsuite - REST API - Making query with Token Based Authentication (TBA) - (in Python)

This is a follow up to the successful call using Netsuite Token Based Authentication (TBA) REST webservice,
I would like to get some guidance on how to perform a query.
I am supposed to read records like this (please see screenshot)
how can I perform a specifc query (by table for a list of records and also specific record) ?
https://gist.github.com/axilaris/4386c3537d04737d3775c156562b7545 <-- here is the python code for the TBA that has worked successful. I would like to know how to construct the next step on how to perform the query and read specific record (as shown in the screenshot).
This is a custom record with an ID like this customrecord1589
To query a specific record: You're going to need to create/ deploy a RESTlet in Netsuite similar to the following:
/**
* #NApiVersion 2.1
* #NScriptType Restlet
*/
define([
"N/log",
"N/search",
], function (log, search) {
function post(context) {
return JSON.stringify(getCustomRecords(context));
}
function getCustomRecords(context) {
log.debug('POST Context', context);
return search.lookupFields({
//Change CUSTOM_RECORD to the type of custom record you are querying
type: search.Type.CUSTOM_RECORD + '1589',
id: context.id,
columns: context.fields,
});
}
return {
post: post,
};
});
In your Python Script: Make sure you change the URL of the request to the deployment URL of this new RESTlet. Also, make sure to pass any parameters you need (like 'id' or 'fields' in my example) in your POST request payload. So instead of:
payload = {
"name":"value",
"foo":"bar",
"duck":"hunt",
}
pass
payload = {
"id":"9999999",
"fields": ["custrecord_field1", "custrecord_field2"],
}
where id is the internalid of the record you want to query and the fields array are the internalids of the fields you want values from.
If this goes successfully, the result should show up as conn.text in your python script!

How can I create a relation in Strapi if I don't know the id of the field?

I am creating a collection of judges and courthouses. Every judge will be assigned to one courthouse. I have set up my relation to be that courthouse has many judges
I am attempting to do this programmatically when the app loads. I have a function that is able to populate all the fields in judge except the relation to courthouse. My function uses the Strapi API like this
const judge = await strapi.query('judge').create({
name: data[i].name,
},
{
courthouse: data[i].courthouse_name // here is where I think the relation is created
}
)
I am passing in a string that has the name of courthouse, because I don't know the ID of the courthouse in the Courthouse collection.
My question is it possible to create a relation to another collection by anything other than an ID? How can I create a relation to a courthouse by its name?
I couldn't find a way around building a relationship between two models without the ID, so I created a custom solution using the Strapi lifecycle hooks
Essentially what I did I utilized the beforeCreate lifecycle hook to query and find the courthouse that matches the name like this:
// judges.js
async beforeCreate(result, data) {
const courthouse = await strapi.query('courthouse').find(
{courthouse_name:data.courthouse}
); // returns the courthouse that matches the name
result['courthouse'] = courthouse[0].id; // populates the relational field with the
// ID of the courthouse
}
The response object contained the courthouse's ID and I manipulated the data that is being sent to the create command like this:
const judge = await strapi.query('judge').create({
name: data[i].name,
courthouse: data[i].courthouse_name
})
The result is an object that looks like this:
{name: 'Garfield Lucas, courthouse: 7463987}

How to get all available field names in Facebook API (get_insights) method?

def get_campaigns_insight(self, start_date, end_date, batch_size):
params = {
'time_range': {'since':start_date,'until':end_date},
'filtering': [],
'level': 'campaign',
'breakdowns': ['country'],
'limit': batch_size,
'date_preset': 'lifetime',
}
fields = ['campaign_name', 'canvas_avg_view_percent']
response = self.account.get_insights(
fields=fields,
params=params,
)
data = str(response)
Currently I am passing the field names in a list and throwing it into the parameters as an argument, this works and i can manually add the names from the documentation, but surely there should be a way to get all the fields available right?
There is no way to get ALL fields, else a lot of users would use the oppertunity and use bandwith they do not really need - because you will most likely not need ALL fields. For all API calls, Facebook only returns a few default fields and additional fields you specify.

Updating Data From MongoDB using Web API

I have a database that created in MongoDB using Robomongo tool. How can I update these data in Web API by its default POST, PUT, DELETE methods in ValuesControllers.cs?
Database name : StudentInfo
Collection Name : Student
{
_id : ObjectId(),
name : "lqbal",
department : "CSE",
phone : "0194949402"
}
Here is an example of the POST Action. WebApi can perform Model binding so it can take content from the body of the POST action and bind it to a c# entity - in this case the Student object.
Here is the content of the Request Body.
{
"name": "lqbal",
"department": "CSEGlobal",
"phone": "0194949402"
}
Also make sure to set the Content-Type of the Reqest to application/json so WebApi can perform the correct model binding.
The code in the POST action then has to look up the student in question in the DB. Once it retrieves the Student object, it can update the values and then save the object back to the DB.
public void Post([FromBody]Student value)
{
var student = ((MongoCollection)collection).AsQueryable<Student>().First(c => c.name == value.name);
student.department = value.department;
student.phone = value.phone;
collection.Save(student);
}
The concept for the PUT action is similar to this POST action except that a new Student object is created.
The DELETE action is straightforward as well is similar to the GET action - you only need to pass the ID of the record to delete in the query string and then just delete it in the action controller.
Here is a link to how to remove a document with the mongo c# driver
Mongo c# Driver - Remove an Existing Document

Yii2 REST API fields (user?fields=id) does not work

I've got the REST API working with the user table provided in the base migration. I can "GET /users" just fine, but according to the docs, I should also be able to "GET /users?fields=id" and receive a response limited to the id fields.
But instead I get the full result set.
Under the topic Fields in Yii2 Guide it says;
// only returns field id and email, provided they are declared in fields()
http://localhost/users?fields=id,email
so you have to override the fields() function to get the expected result.
// explicitly list every field, best used when you want to make sure the changes
// in your DB table or model attributes do not cause your field changes (to keep API backward compatibility).
public function fields()
{
return [
// field name is the same as the attribute name
'id',
// field name is "email", the corresponding attribute name is "email_address"
'email' => 'email_address',
// field name is "name", its value is defined by a PHP callback
'name' => function ($model) {
return $model->first_name . ' ' . $model->last_name;
},
];
}