Add User
Purpose
To add a user to your organization.
Endpoints
Request Details
Request URL
https://www.zohoapis.com/crm/v2/users
Header
Authorization: Zoho-oauthtoken d92d4xxxxxxxxxxxxx15f52
Scope
scope=ZohoCRM.users.{operation_type}
Possible operation types
ALL - Full access to users
CREATE - To create users
You can add only one user per POST request.
Adding a CRM Plus user through API is not supported. You can only add a CRM Plus user through the UI.
You must use only Field API names in the input. You can obtain the field API names from Fields metadata API (the value for the key “api_name” for every field).
Sample Request
Copiedcurl "https://www.zohoapis.com/crm/v2/users"
-H "Authorization: Zoho-oauthtoken 1000.8cb99dxxxxxxxxxxxxx9be93.9b8xxxxxxxxxxxxxxxf"
-d "@newuser.json"
-X POST
Copied//Get instance of UsersOperations Class
UsersOperations usersOperations = new UsersOperations();
//Get instance of BodyWrapper Class that will contain the request body
RequestWrapper request = new RequestWrapper();
//List of User instances
List < com.zoho.crm.api.users.User > userList = new ArrayList < com.zoho.crm.api.users.User > ();
//Get instance of User Class
com.zoho.crm.api.users.User user1 = new com.zoho.crm.api.users.User();
Role role = new Role();
role.setId(3477061000000026008 L);
user1.setRole(role);
user1.setFirstName("TestUser");
user1.setEmail("testuser1@zoho.com");
Profile profile = new Profile();
profile.setId(3477061000000026014 L);
user1.setProfile(profile);
user1.setLastName("12");
userList.add(user1);
request.setUsers(userList);
//Call createUser method that takes BodyWrapper class instance as parameter
APIResponse < ActionHandler > response = usersOperations.createUser(request);
Copiedpackage com.zoho.crm.api.sample.restapi.users;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
public class AddUser
{
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
try
{
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
SSLContext sslContext = SSLContext.getDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory).build();
URIBuilder uriBuilder = new URIBuilder("https://www.zohoapis.com/crm/v2/users");
HttpUriRequest requestObj = new HttpPost(uriBuilder.build());
HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) requestObj;
JSONObject requestBody = new JSONObject();
JSONArray userArray = new JSONArray();
JSONObject userObject = new JSONObject();
userObject.put("role", "34770610026008");
userObject.put("first_name", "Patricia");
userObject.put("email", "Patricia@abcl.com");
userObject.put("profile", "34770610026014");
userObject.put("last_name", "Boyle");
userArray.put(userObject);
requestBody.put("users", userArray);
requestBase.setEntity(new StringEntity(requestBody.toString(), HTTP.UTF_8));
requestObj.addHeader("Authorization", "Zoho-oauthtoken 1000.xxxxxxx.xxxxxxx");
HttpResponse response = httpclient.execute(requestObj);
HttpEntity responseEntity = response.getEntity();
System.out.println("HTTP Status Code : " + response.getStatusLine().getStatusCode());
if(responseEntity != null)
{
Object responseObject = EntityUtils.toString(responseEntity);
String responseString = responseObject.toString();
System.out.println(responseString);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Copied//Get instance of UsersOperations Class
$usersOperations = new UsersOperations();
//Get instance of BodyWrapper Class that will contain the request body
$request = new RequestWrapper();
//List of User instances
$userList = array();
$userClass = "com\zoho\crm\api\users\User";
//Get instance of User Class
$user1 = new $userClass();
$role = new Role();
$role->setId("3477061000000026008");
$user1->setRole($role);
$user1->setFirstName("TestUser");
$user1->setEmail("testuser@zoho.com");
$profile = new Profile();
$profile->setId("3477061000000026014");
$user1->setProfile($profile);
$user1->setLastName("12");
array_push($userList, $user1);
$request->setUsers($userList);
//Call createUser method that takes BodyWrapper class instance as parameter
$response = $usersOperations->createUser($request);
Copied<?php
class AddUser
{
public function execute(){
$curl_pointer = curl_init();
$curl_options = array();
$curl_options[CURLOPT_URL] = "https://www.zohoapis.com/crm/v2/users";
$curl_options[CURLOPT_RETURNTRANSFER] = true;
$curl_options[CURLOPT_HEADER] = 1;
$curl_options[CURLOPT_CUSTOMREQUEST] = "POST";
$requestBody = array();
$userArray = array();
$userObject = array();
$userObject["role"]="3524033000000026005";
$userObject["first_name"]="Variaggble33";
$userObject["email"] = "asda@asd.com";
$userObject["profile"] = "3524033000000026011";
$userObject["last_name"] = "sadasd";
$userArray[] = $userObject;
$requestBody["users"] =$userArray;
$curl_options[CURLOPT_POSTFIELDS]= json_encode($requestBody);
$headersArray = array();
$headersArray[] = "Authorization". ":" . "Zoho-oauthtoken " . "1000.f62eXXXXXXXXXXXXXXXXXX2a293.0af1XXXXXXXXXXXXc54ee827beb";
$curl_options[CURLOPT_HTTPHEADER]=$headersArray;
curl_setopt_array($curl_pointer, $curl_options);
$result = curl_exec($curl_pointer);
$responseInfo = curl_getinfo($curl_pointer);
curl_close($curl_pointer);
list ($headers, $content) = explode("\r\n\r\n", $result, 2);
if(strpos($headers," 100 Continue")!==false){
list( $headers, $content) = explode( "\r\n\r\n", $content , 2);
}
$headerArray = (explode("\r\n", $headers, 50));
$headerMap = array();
foreach ($headerArray as $key) {
if (strpos($key, ":") != false) {
$firstHalf = substr($key, 0, strpos($key, ":"));
$secondHalf = substr($key, strpos($key, ":") + 1);
$headerMap[$firstHalf] = trim($secondHalf);
}
}
$jsonResponse = json_decode($content, true);
if ($jsonResponse == null && $responseInfo['http_code'] != 204) {
list ($headers, $content) = explode("\r\n\r\n", $content, 2);
$jsonResponse = json_decode($content, true);
}
var_dump($headerMap);
var_dump($jsonResponse);
var_dump($responseInfo['http_code']);
}
}
(new AddUser())->execute();
Copied//Get instance of UsersOperations Class
UsersOperations usersOperations = new UsersOperations();
//Get instance of RequestWrapper Class that will contain the request body
RequestWrapper request = new RequestWrapper();
//List of User instances
List<Com.Zoho.Crm.API.Users.User> userList = new List<Com.Zoho.Crm.API.Users.User>();
//Get instance of User Class
Com.Zoho.Crm.API.Users.User user1 = new Com.Zoho.Crm.API.Users.User();
API.Roles.Role role = new API.Roles.Role();
role.Id = 347706126008;
user1.Role = role;
user1.FirstName = "TestUser";
user1.Email = "testuser1@zoho.com";
API.Profiles.Profile profile = new API.Profiles.Profile();
profile.Id = 3477061026014;
user1.Profile = profile;
user1.LastName = "12";
userList.Add(user1);
request.Users = userList;
//Call CreateUser method that takes BodyWrapper class instance as parameter
APIResponse<ActionHandler> response = usersOperations.CreateUser(request);
Copiedusing System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Com.Zoho.Crm.API.Sample.RestAPI.Users
{
public class AddUser
{
public static void InsertUser()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.zohoapis.com/crm/v2/users");
request.Method = "POST";
request.Headers["Authorization"] = "Zoho-oauthtoken 1000.abfeXXXXXXXXXXX2asw.XXXXXXXXXXXXXXXXXXsdc2";
JObject requestBody = new JObject();
JArray userArray = new JArray();
JObject userObject = new JObject();
userObject.Add("role", "347706126008");
userObject.Add("first_name", "Patricia");
userObject.Add("email", "Patricia@abcl.com");
userObject.Add("profile", "347706126014");
userObject.Add("last_name", "Boyle");
userArray.Add(userObject);
requestBody.Add("users", userArray);
string dataString = requestBody.ToString();
var data = Encoding.UTF8.GetBytes(dataString);
int dataLength = data.Length;
request.ContentLength = dataLength;
using (var writer = request.GetRequestStream())
{
writer.Write(data, 0, dataLength);
}
request.KeepAlive = true;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if (e.Response == null) { throw; }
response = (HttpWebResponse)e.Response;
}
HttpWebResponse responseEntity = response;
Console.WriteLine("HTTP Status Code : " + (int)response.StatusCode);
string responsestring = new StreamReader(responseEntity.GetResponseStream()).ReadToEnd();
responseEntity.Close();
Console.WriteLine(responsestring);
}
}
}
Copied# Get instance of UsersOperations Class
users_operations = UsersOperations()
# Get instance of RequestWrapper Class that will contain the request body
request = RequestWrapper()
# List to hold User instances
user_list = []
# Get instance of User Class
user = ZCRMUser()
# Get instance of Role Class
role = Role()
# Set ID to Role instance
role.set_id(3477061000000026008)
# Set role instance to role in User
user.set_role(role)
user.set_country_locale('en_US')
user.set_first_name('Test')
user.set_last_name('User')
user.set_email('testuser@zoho.com')
# Get instance of Profile Class
profile = Profile()
# Set ID to Profile instance
profile.set_id(3477061000000026014)
# Set profile instance to profile in User instance
user.set_profile(profile)
# Add the User instance to list
user_list.append(user)
# Set the list to users in BodyWrapper instance
request.set_users(user_list)
# Call create_user method that takes RequestWrapper class instance as parameter
response = users_operations.create_user(request)
Copieddef add_user():
import requests
import json
url = 'https://www.zohoapis.com/crm/v2/users'
headers = {
'Authorization': 'Zoho-oauthtoken 1000.04be928e4a96XXXXXXXXXXXXX68.0b9eXXXXXXXXXXXX60396e268',
}
request_body = dict()
user_list = list()
user_object = {
'role': '3409643000000026005',
'first_name': 'Patricia',
'last_name': 'Boyle',
'profile': '3409643000000026011',
'email': 'Patricia@abcl.com'
}
user_list.append(user_object)
request_body['users'] = user_list
response = requests.post(url=url, headers=headers, data=json.dumps(request_body).encode('utf-8'))
if response is not None:
print("HTTP Status Code : " + str(response.status_code))
print(response.json())
add_user()
Copied//Get instance of UsersOperations Class
let usersOperations = new UsersOperations();
//Get instance of RequestWrapper Class that will contain the request body
let request = new RequestWrapper();
//Array to hold User instances
let userArray = [];
//Get instance of User Class
let user = new User();
//Get instance of Role Class
let role = new Role();
//Set ID to Role instance
role.setId(340964026008n);
//Set Role instance to role in User
user.setRole(role);
user.setCountryLocale("en_US");
user.setFirstName("Test");
user.setLastName("User");
user.setEmail("testuser@zoho.com");
//Get instance of Profile Class
let profile = new Profile();
profile.setId(3409643395047n);
//Set profile instance to profile in User instance
user.setProfile(profile);
//Add the User instance to array
userArray.push(user);
//Set the array to users in RequestWrapper instance
request.setUsers(userArray);
//Call createUser method that takes RequestWrapper class instance as parameter
let response = await usersOperations.createUser(request);
Copiedasync function addUser() {
const got = require("got");
let url = 'https://www.zohoapis.com/crm/v2/users'
let headers = {
Authorization : "Zoho-oauthtoken 1000.8cb99dxxxxxxxxxxxxx9be93.9b8xxxxxxxxxxxxxxxf"
}
let requestBody = {}
let userArray = []
let userObject = {
'role': '3409643000000026005',
'first_name': 'Patricia',
'last_name': 'Boyle',
'profile': '3409643000000026011',
'email': 'Patricia@abcl.com'
}
userArray.push(userObject)
requestBody['users'] = userArray
let requestDetails = {
method : "POST",
headers : headers,
body : JSON.stringify(requestBody),
encoding: "utf8",
throwHttpErrors : false
};
let response = await got(url, requestDetails)
if(response != null) {
console.log(response.statusCode);
console.log(response.body);
}
}
addUser()
Copiedusers = []
# Get instance of Role Class
role = Roles::Role.new
# Set ID to Role instance
role.id = 3_524_033_000_000_026_011
# Set profile instance to profile in User instance
profile = Profiles::Profile.new
profile.id = 3_524_033_000_000_026_011
# Get instance of User Class
user = Users::User.new
# Get instance of Profile Class
user.profile = profile
# Set role instance to role in User
user.role = role
user.first_name = '1'
user.last_name = '1'
user.email = '1@zoho.com'
# Set the list to users in BodyWrapper instance
users.push(user)
# Get instance of RequestWrapper Class that will contain the request body
rw = Users::RequestWrapper.new
# List to hold User instances
rw.users = users
# Get instance of UsersOperations Class
uo = Users::UsersOperations.new
response = uo.create_user(rw)
Copiedclass AddUser
def execute
url = URI( "https://www.zohoapis.com/crm/v2/users")
req = Net::HTTP::Post.new(url.request_uri)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
headers={}
headers["Authorization"]="Zoho-oauthtoken 1000.50XXXXXXXXX&77e3a.44XXXXXXXXX8353"
headers&.each { |key, value| req.add_field(key, value) }
request_body = {};
users_array = [];
user_object = {};
user_object["role"]="3524033000000026005";
user_object["first_name"]="Variaggble33";
user_object["email"] = "asda@asd.com";
user_object["profile"] = "3524033000000026011";
user_object["last_name"] = "sadasd";
users_array = [user_object];
request_body["users"] =users_array;
request_json = request_body.to_json
req.body = request_json.to_s
response=http.request(req)
status_code = response.code.to_i
headers = response.each_header.to_h
print status_code
print headers
unless response.body.nil?
print response.body
end
end
end
AddUser.new.execute
Copied//Get instance of UsersOperations Class
let usersOperations = new ZCRM.User.Operations();
//Get instance of RequestWrapper Class that will contain the request body
let request = new ZCRM.User.Model.RequestWrapper();
//Array to hold User instances
let userArray = [];
//Get instance of User Class
let user = new ZCRM.User.Model.User();
//Get instance of Role Class
let role = new ZCRM.Role.Model.Role();
//Set ID to Role instance
role.setId(347706126008n);
//Set Role instance to role in User
user.setRole(role);
user.setCountryLocale("en_US");
user.setFirstName("Test");
user.setLastName("User");
user.setEmail("testuser123@zoho.com");
//Get instance of Profile Class
let profile = new ZCRM.Profile.Model.Profile();
profile.setId(347706126014n);
//Set profile instance to profile in User instance
user.setProfile(profile);
//Add the User instance to array
userArray.push(user);
//Set the array to users in RequestWrapper instance
request.setUsers(userArray);
//Call createUser method that takes RequestWrapper class instance as parameter
let response = await usersOperations.createUser(request);
Copiedvar listener = 0;
class AddUser {
async insertUser() {
var url = "https://www.zohoapis.com/crm/v2/users"
var parameters = new Map()
var headers = new Map()
var token = {
clientId:"1000.NPY9M1V0XXXXXXXXXXXXXXXXXXXF7H",
redirectUrl:"http://127.0.0.1:5500/redirect.html",
scope:"ZohoCRM.users.ALL,ZohoCRM.bulk.read,ZohoCRM.modules.ALL,ZohoCRM.settings.ALL,Aaaserver.profile.Read,ZohoCRM.org.ALL,profile.userphoto.READ,ZohoFiles.files.ALL,ZohoCRM.bulk.ALL,ZohoCRM.settings.variable_groups.ALL"
}
var accesstoken = await new AddUser().getToken(token)
headers.set("Authorization", "Zoho-oauthtoken " + accesstoken)
var requestMethod = "POST"
var reqBody = {"users":[
{
"email": "Patricsdia@abcl.com",
"first_name":"Patricia",
"role": "352403326005",
"profile": "352403326011",
"last_name": "Boyle"
}
]}
var params = "";
parameters.forEach(function(value, key) {
if (parameters.has(key)) {
if (params) {
params = params + key + '=' + value + '&';
}
else {
params = key + '=' + value + '&';
}
}
});
var apiHeaders = {};
if(headers) {
headers.forEach(function(value, key) {
apiHeaders[key] = value;
});
}
if (params.length > 0){
url = url + '?' + params.substring(0, params.length - 1);
}
var requestObj = {
uri : url,
method : requestMethod,
headers : apiHeaders,
body : JSON.stringify(reqBody),
encoding: "utf8",
allowGetBody : true,
throwHttpErrors : false
};
var result = await new AddUser().makeAPICall(requestObj);
console.log(result.status)
console.log(result.response)
}
async getToken(token) {
if(listener == 0) {
window.addEventListener("storage", function(reponse) {
if(reponse.key === "access_token" && (reponse.oldValue != reponse.newValue || reponse.oldValue == null)){
location.reload();
}
if(reponse.key === "access_token"){
sessionStorage.removeItem("__auth_process");
}
}, false);
listener = 1;
if(sessionStorage.getItem("__auth_process")) {
sessionStorage.removeItem("__auth_process");
}
}
["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
var isKeyExists = localStorage.hasOwnProperty(k);
if(isKeyExists) {
sessionStorage.setItem(k, localStorage[k]);
}
localStorage.removeItem(k);
});
var valueInStore = sessionStorage.getItem("access_token");
var tokenInit = sessionStorage.getItem("__token_init");
if(tokenInit != null && valueInStore != null && Date.now() >= parseInt(tokenInit) + 59 * 60 * 1000){ // check after 59th minute
valueInStore = null;
sessionStorage.removeItem("access_token");
}
var auth_process = sessionStorage.getItem("__auth_process");
if ((valueInStore == null && auth_process == null) || (valueInStore == 'undefined' && (auth_process == null || auth_process == "true"))) {
var accountsUrl = "https://accounts.zoho.com/oauth/v2/auth"
var clientId;
var scope;
var redirectUrl;
if(token != null) {
clientId = token.clientId;
scope = token.scope;
redirectUrl = token.redirectUrl;
}
var fullGrant = sessionStorage.getItem("full_grant");
var grantedForSession = sessionStorage.getItem("granted_for_session");
if(sessionStorage.getItem("__token_init") != null && ((fullGrant != null && "true" == full_grant) || (grantedForSession != null && "true" == grantedForSession))) {
accountsUrl += '/refresh';
}
if (clientId && scope) {
sessionStorage.setItem("__token_init", Date.now());
sessionStorage.removeItem("access_token");
sessionStorage.setItem("__auth_process", "true");
window.open(accountsUrl + "?" + "scope" + "=" + scope + "&"+ "client_id" +"=" + clientId + "&response_type=token&state=zohocrmclient&redirect_uri=" + redirectUrl);
["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
var isKeyExists = localStorage.hasOwnProperty(k);
if(isKeyExists){
sessionStorage.setItem(k, localStorage[k]);
}
localStorage.removeItem(k);
});
valueInStore = sessionStorage.getItem("access_token");
}
}
if(token != null && valueInStore != 'undefined'){
token.accessToken = valueInStore;
}
return token.accessToken;
}
async makeAPICall(requestDetails) {
return new Promise(function (resolve, reject) {
var body, xhr, i;
body = requestDetails.body || null;
xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open(requestDetails.method, requestDetails.uri, true);
for (i in requestDetails.headers) {
xhr.setRequestHeader(i, requestDetails.headers[i]);
}
xhr.send(body);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
resolve(xhr);
}
}
})
}
}
Copieduser1 = Map();
user1.put("last_name", "Shawn");
user1.put("email", "shawn@zylker.com");
user1.put("role", "692969000000015969");
user1.put("profile", "692969000000015972");
users = List();
users.add(user1);
params = Map();
params.put("users", users);
response = invokeurl
[
url: "https://www.zohoapis.com/crm/v2/users"
type: POST
parameters: params.toString()
connection:"crm_connection"
];
info response ;
In the request, "@newuser.json" contains the sample input data.
Request JSON
- last_namestring, mandatory
Specify the last name of the user.
- emailstring, mandatory
Specify the email ID of the user.
- rolestring, mandatory
Specify the unique ID of the role you want to assign the user with. You can obtain the role ID from the Roles API.
- profilestring, mandatory
Specify the unique ID of the profile you want to assign the user with, to decide the user's level of access to CRM data. You can obtain the profile ID from the Profiles API.
Refer to Add Records API to know about the field types and limitations.
Sample Input
Copied{
"users": [
{
"role": "554023000000015969",
"first_name": "Patricia",
"email": "Patricia@abcl.com",
"profile": "554023000000015975",
"last_name": "Boyle"
}
]
}
Possible Errors
- INVALID_REQUESTHTTP 400
Cannot add user under CRM Plus account. Kindly use CRMPlus URL to add user.
Resolution: Adding a CRM Plus user through API is not supported. You can only add a CRM Plus user through the UI. Refer to the note section above. - LICENSE_LIMIT_EXCEEDEDHTTP 400
Request exceeds your license limit. Need to upgrade in order to add.
Resolution: The maximum number of users you can add per your CRM plan has exceeded. Please buy additional user licenses to add more users. - DUPLICATE_DATAHTTP 400
Failed to add user since same email id is already present
Resolution: You have entered a duplicate value for the email_id. Make sure you give unique values for the email_id and last_name fields. - MANDATORY_NOT_FOUNDHTTP 400
Last Name is required
Resolution: You have not specified one of the mandatory keys. Refer to request JSON section above. - INVALID_DATAHTTP 400
Invalid data. Valid values are comma/space/period/none.
Resolution: The key value specified is invalid. It can contain only the above mentioned special characters. - FORBIDDENHTTP 403
Permission denied
Resolution: Only the users with user profile is "administrator" can add new users. Contact your system administrator. - INVALID_URL_PATTERNHTTP 404
Please check if the URL trying to access is a correct one
Resolution: The request URL specified is incorrect. Specify a valid request URL. Refer to request URL section above. - OAUTH_SCOPE_MISMATCHHTTP 401
Unauthorized
Resolution: Client does not have ZohoCRM.users.CREATE scope. Create a new client with valid scope. Refer to scope section above. - NO_PERMISSIONHTTP 403
Permission denied to create
Resolution: The user does not have permission to create user records. Contact your system administrator. - INTERNAL_ERRORHTTP 500
Internal Server Error
Resolution: Unexpected and unhandled exception in the server. Contact support team. - INVALID_REQUEST_METHODHTTP 400
The http request method type is not a valid one
Resolution: You have specified an invalid HTTP method to access the API URL. Specify a valid request method. Refer to endpoints section above. - AUTHORIZATION_FAILEDHTTP 400
User does not have sufficient privilege to add new users
Resolution: The user does not have the permission to add users. Contact your system administrator.
Sample Response
Copied{
"users": [
{
"code": "SUCCESS",
"details": {
"id": "554023000000691003"
},
"message": "User added",
"status": "success"
}
]
}