Integrating Django with Salesforce
Salesforce is a customer success platform with their CRM solution leading the CRM market for a considerable time. Salesforce offers many Services(SaaS) and Products(PaaS) which aid in the efficient functioning of organizations by providing smoother integration between various departments. Salesforce offers a range of features in functional areas of a company, including sales, marketing, customer support, team performance data, etc., and has proven itself as an indispensable tool.
Apart from the traditional approach of feeding data manually into Salesforce, it can also be integrated with other systems to extend its functionality for a faster and more efficient method of transferring/updating data using automation. In this blog, I will discuss one such approach for integrating a Django application with Salesforce using its APIs.
Nowadays, APIs are the heart of every application which is why they are being developed at a brisk pace. The Django-REST-framework, which I intend to use, is one such framework that makes the process of building RESTful API requests (web) simpler and allows more flexibility. RESTful APIs allow users and servers to communicate with each other using CRUD operations.
You can create RESTful APIs and integrate them with Salesforce with the following steps:
1. Create a project:
django-admin startproject projectname
After completion of project creation, change the parent directory to the project directory.
2. Create an application:
python manage.py startapp appname
3. Install rest_framework and simple_salesforce packages:
pip Install djangorestframework pip install simple_salesforce
4. Add the Salesforce app, the created app, and rest_framework to your INSTALLED_APPS in the settings module of the project by using the following commands:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', ………. 'appname', 'rest_framework', 'salesforce', )
5. Create a model for the object in models.py in the application directory:
A model contains details of essential fields and behaviors of the data you store into the database.
class Classname(models.Model): Parameter = models.CharField(max_length=50, blank=False, null=False) def __str__(self): Return self.Parameter
6. Create a serializer to convert native Python data type to JSON data to reflect on the browser:
Serializers allow querysets and model instances to be converted to native Python data types. This helps in rendering these complex data types into JSON, XML, or other content types. Once the validation of incoming data is completed, you can convert the parsed data back into a complex type. This is called deserialization.
class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__'
7. Instantiate a Salesforce object to authenticate and login to Salesforce:
To login using IP-whitelist organization ID method, simply use your Salesforce username, password, and organization ID
from simple_salesforce import Salesforce def login(): return Salesforce( username=SALESFORCE_USERNAME, password=SALESFORCE_PASSWORD, organizationId=SALESFORCE_SECURITY_TOKEN)
To login to Salesforce sandbox, add security_token and domain as ‘test’:
In Salesforce account:
- USER is the username of the Salesforce account.
- PASSWORD is a concatenation of the user's password.
- SECURITY TOKEN can be omitted if the local IP address has been whitelisted in Security Controls / Network Access.
- The domain is ‘test’
- HOST is https://test.salesforce.com to access a sandbox.
8. Now, attempt to use the created Salesforce object to create a contact on Salesforce with REST API:
9. To map these APIs, create a router file that will dispatch the API EndPoints:
from rest_framework import routers from myapp.views import ContactViewSet router = routers.SimpleRouter() router.register(r'\', ContactViewSet)
10. Map this router with url.py in the project directory:
from django.conf.urls import include, url from django.contrib import admin from myproject.routers import router urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include(router.urls)), ]
11. Then, create migrations for the created object in the database and migrate those tables with the database by using the below commands:
python manage.py makemigrations python manage.py migrate
12. Finally, run the project server:
Python manage.py runserver
Now, go to the browser and hit the contact url.
You should be able to see the API to create a contact in Salesforce.
To perform CRUD operations in Salesforce, you can use the following Salesforce Object Query Language (SOQL) queries:
- To create a new 'Contact' in Salesforce:
sf.Contact.create({‘LastName’:’Smith’, ‘Email’:’example@example.com’})
- To get a dictionary with all the information regarding ‘contact’ record, use:
sf.Contact.get_by_custom_id('My_Custom_ID__c', '22')
- To change that contact's last name from 'Smith' to 'Jones' and add a first name as 'John', use:
sf.Contact.update('003e0000003GuNXAA0',{'LastName': 'Jones', 'FirstName': 'John'})
- To delete the contact:
sf.Contact.delete('003e0000003GuNXAA0')
It's also possible to write select queries in Salesforce Object Query Language (SOQL) and search queries in Salesforce Object Search Language (SOSL).
SOSL queries can be done in two ways:
- To retrieve basic metadata, use:
sf.Contact.metadata()
- To retrieve a description of the object, use:
sf.Contact.describe()
These are the related queries to perform operations on an object in Salesforce.
You should now have a functioning API using the Django REST framework Request and Response objects. And you have an extended API to handle different format suffixes and to POST data via the API.
You can also check out a sample application code here:
https://github.com/manoharroyal/myprojectSF.git