Update User

Purpose

To update the details of a user of your organization.

Request Details

Request URL

https://www.zohoapis.com/crm/v2/users

To update a specific user
https://www.zohoapis.com/crm/v2/users/{user_id}

Header

Authorization: Zoho-oauthtoken d92d4xxxxxxxxxxxxx15f52

Scope

scope=ZohoCRM.users.{operation_type}

Possible operation types

ALL - Full access to users
UPDATE - Update user data

Note

You can update only one user's details per PUT request.

Sample Request

Copiedcurl "https://www.zohoapis.com/crm/v2/users"
-H "Authorization: Zoho-oauthtoken 1000.8cb99dxxxxxxxxxxxxx9be93.9b8xxxxxxxxxxxxxxxf"
-d "@updateuser.json"
-X PUT
3.0.08.0
Copied//Get instance of UsersOperations Class
UsersOperations usersOperations = new UsersOperations();

//Get instance of BodyWrapper Class that will contain the request body
BodyWrapper request = new BodyWrapper();

//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();

user1.setId(3477061000005791024 L);

Role role = new Role();

role.setId(3477061000000026008 L);

user1.setRole(role);

user1.setCountryLocale("en_US");

userList.add(user1);

user1 = new com.zoho.crm.api.users.User();

user1.setId(3477061000005791024 L);

role = new Role();

role.setId(3477061000000026008 L);

user1.setRole(role);

user1.setCountryLocale("en_US");

//		user1.addKeyValue(apiName, value);

userList.add(user1);

request.setUsers(userList);

//Call updateUsers method that takes BodyWrapper instance as parameter
APIResponse < ActionHandler > response = usersOperations.updateUsers(request);
Copiedimport 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.HttpPut;
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 UpdateUser 
{
	@SuppressWarnings("deprecation")
	private static void updateUsers()
	{
		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 HttpPut(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");
			userObject.put("id", "34770617745001");
			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();
		}
	}
	@SuppressWarnings("deprecation")
	private static void updateUser()
	{
		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/34770617745001");
			HttpUriRequest requestObj = new HttpPut(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", "Boyle1");
			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();
		}
	}
	public static void main(String[] args) 
	{
		updateUsers();
		updateUser();
	}
}
3.0.07.x
Copied//Get instance of UsersOperations Class
$usersOperations = new UsersOperations();
//Get instance of BodyWrapper Class that will contain the request body
$request = new BodyWrapper();
//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("34770610XXXXXXXX026008");
$user1->setRole($role);
$user1->setCountryLocale("en_US");
array_push($userList, $user1);
$request->setUsers($userList);
//Call updateUser method that takes BodyWrapper instance and userId as parameter
$response = $usersOperations->updateUser($userId,$request);
Copied<?php

class UpdateUser
{
    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] = "PUT";
        $requestBody = array();
        $userArray = array();
        $userObject = array();
    
        $userObject["last_name"] = "sadasd";
        $userObject["id"]="3524033000006016001";
        $userArray[] = $userObject;
        $requestBody["users"] =$userArray;
        $curl_options[CURLOPT_POSTFIELDS]= json_encode($requestBody);
        $headersArray = array();
        
        $headersArray[] = "Authorization". ":" . "Zoho-oauthtoken " . "1000.8cb99dxxxxxxxxxxxxx9be93.9b8xxxxxxxxxxxxxxxf";
        
        $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 UpdateUser())->execute();
3.0.08.x
Copied//Get instance of UsersOperations Class
UsersOperations usersOperations = new UsersOperations();
//Get instance of BodyWrapper Class that will contain the request body
BodyWrapper request = new BodyWrapper();
//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();
user1.Id = 34770615791024;
API.Roles.Role role = new API.Roles.Role();
role.Id = 347706126008;
user1.Role = role;
user1.CountryLocale = "en_US";
userList.Add(user1);
user1 = new Com.Zoho.Crm.API.Users.User();
user1.Id = 3477061791024;
role = new API.Roles.Role();
role.Id = 347706126008;
user1.Role = role;
user1.CountryLocale = "en_US";
//user1.AddKeyValue("apiName", "value");
userList.Add(user1);
request.Users = userList;
//Call UpdateUsers method that takes BodyWrapper instance as parameter
APIResponse<ActionHandler> response = usersOperations.UpdateUsers(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 UpdateUser
    {
        public static void UpdateUsers()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.zohoapis.com/crm/v2/users");
            request.Method = "PUT";
            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");
            userObject.Add("id", "34770617848011");
            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);
        }
        public static void UpdateSingleUser()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.zohoapis.com/crm/v2/users/3477061000007848011");
            request.Method = "PUT";
            request.Headers["Authorization"] = "Zoho-oauthtoken 1000.abfeXXXXXXXXXXX2asw.XXXXXXXXXXXXXXXXXXsdc2";
            JObject requestBody = new JObject();
            JArray userArray = new JArray();
            JObject userObject = new JObject();
            userObject.Add("role", "3477061026008");
            userObject.Add("first_name", "Patricia");
            userObject.Add("email", "Patricia@abcl.com");
            userObject.Add("profile", "3477061026014");
            userObject.Add("last_name", "Boyle1");
            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);
        }
        public static void UpdateNotesofASpecificRecord()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.zohoapis.com/crm/v2/Leads/34770617736020/Notes");
            request.Method = "PUT";
            request.Headers["Authorization"] = "Zoho-oauthtoken 1000.3048fdXXXXXXXXXXXXX940ab.a80f2XXXXXXXXXXXXXXXb67a23";
            JObject requestBody = new JObject();
            JArray recordArray = new JArray();
            JObject recordObject = new JObject();
            recordObject.Add("id", "3477061772009");
            recordObject.Add("Note_Title", "Contacted11");
            recordObject.Add("Note_Content", "Tracking done. Happy with the customer");
            recordArray.Add(recordObject);
            recordObject = new JObject();
            recordObject.Add("id", "3477061772010");
            recordObject.Add("Note_Title", "Contacted12");
            recordObject.Add("Note_Content", "Tracking done. Happy with the customer");
            recordArray.Add(recordObject);
            requestBody.Add("data", recordArray);
            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);
        }
    }
}
3.0.03.x.x
Copied"""
This method is used to update the details of multiple users of your organization and print the response.
"""

# Get instance of UsersOperations Class
users_operations = UsersOperations()

# Get instance of BodyWrapper Class that will contain the request body
request = BodyWrapper()

# List to hold User instances
user_list = []

# Get instance of User Class
user_1 = ZCRMUser()

# Set ID to User instance
user_1.set_id(3477061000011244009)

# Get instance of Role Class
role = Role()

# Set ID to Role instance
role.set_id(3477061000000026008)

# Set role instance to role in User
user_1.set_role(role)

user_1.set_country_locale('en_US')

# Add User instance to list
user_list.append(user_1)

# Get instance of User Class
user_2 = ZCRMUser()

# Set ID to User instance
user_2.set_id(3409643000000302042)

# Get instance of Role Class
role = Role()

# Set ID to Role instance
role.set_id(3409643000000026008)

# Set role instance to role in User
user_2.set_role(role)

user_2.set_country_locale('en_US')

# Add User instance to list
user_list.append(user_2)

# Set the list to users in BodyWrapper
request.set_users(user_list)

# Call update_users method that takes BodyWrapper instance as parameter
response = users_operations.update_users(request)
Copieddef update_users():
    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_1 = {
        'role': '3409643000000026005',
        'id': '3409643000000302031'
    }

    user_object_2 = {
        'id': '3409643000000302042',
        'email': 'user@abcl.com'
    }

    user_list.append(user_object_1)
    user_list.append(user_object_2)

    request_body['users'] = user_list

    response = requests.put(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())

update_users()

def update_user():
    import requests
    import json

    url = 'https://www.zohoapis.com/crm/v2/users/3409643000000302042'

    headers = {
        'Authorization': 'Zoho-oauthtoken 1000.04be928e4a96XXXXXXXXXXXXX68.0b9eXXXXXXXXXXXX60396e268',
    }

    request_body = dict()
    user_list = list()

    user_object = {
        'email': 'user@abcl.com',
        'role': '3409643000000026005'
    }

    user_list.append(user_object)

    request_body['users'] = user_list

    response = requests.put(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())

update_user()
1.0.010.x
Copied//Get instance of UsersOperations Class
let usersOperations = new UsersOperations();
//Get instance of BodyWrapper Class that will contain the request body
let request = new BodyWrapper();
//Array to hold User instances
let userArray = [];
//Get instance of User Class
let user = new User();
//Set ID to User instance
user.setId(3409643302031n);
//Get instance of Role Class
let role = new Role();
//Set ID to Role instance
role.setId(340964326008n);
//Set role instance to role in User
user.setRole(role);
user.setCountryLocale("en_US");
//Add User instance to array
userArray.push(user);
//Get instance of User Class
user = new User();
//Set ID to Role instance
user.setId(3409643302042n);
role = new Role();
//Set ID to Role instance
role.setId(340964326008n);
//Set role instance to role in User
user.setRole(role);
//Add User instance to array
userArray.push(user);
//Set the array to users in BodyWrapper
request.setUsers(userArray);
//Call updateUsers method that takes BodyWrapper instance as parameter
let response = await usersOperations.updateUsers(request);
Copiedasync function updateUsers() {
    const got = require("got");

    let url = 'https://www.zohoapis.com/crm/v2/users'

    let headers = {
        Authorization : "Zoho-oauthtoken 1000.abfeXXXXXXXXXXX2asw.XXXXXXXXXXXXXXXXXXsdc2"
    }

    let requestBody = {}
    let userArray = []

    let userObject1 = {
        'role': '3409643000000026005',
        'id': '3409643000000302031'
    }

    let userObject2 = {
        'id': '3409643000000302042',
        'email': 'user@abcl.com'
    }

    userArray.push(userObject1)
    userArray.push(userObject2)

    requestBody['users'] = userArray

    let requestDetails = {
        method : "PUT",
        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);
    }
}
updateUsers()

async function updateUser() {
    const got = require("got");

    let url = 'https://www.zohoapis.com/crm/v2/users/3409643000000302042'

    let headers = {
        Authorization : "Zoho-oauthtoken 1000.8cb99dxxxxxxxxxxxxx9be93.9b8xxxxxxxxxxxxxxxf"
    }

    let requestBody = {}
    let userArray = []

    let userObject = {
        'email': 'user@abcl.com',
        'role': '3409643000000026005'
    }

    userArray.push(userObject)

    requestBody['users'] = userArray

    let requestDetails = {
        method : "PUT",
        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);
    }
}
updateUser()
2.02.x.x
Copiedusers = []
user_id = 3_524_033_000_003_523_022
# Get instance of Role Class
role = Roles::Role.new
# Set ID to Role instance
role.id = 3_524_033_000_000_026_005
# Get instance of Profile Class
profile = Profiles::Profile.new
# Set ID to Profile instance
profile.id = 3_524_033_000_000_026_011
# Get instance of User Class
user = Users::User.new
# set instance of Profile Class to User
user.profile = profile
# set instance of Role Class to User
user.role = role
user.first_name = '1'
# Set ID to User instance
user.id = user_id
user.last_name = '1'
user.email = '1@zoho.com'
users.push(user)
# Get instance of BodyWrapper Class that will contain the request body
body_wrapper = Users::BodyWrapper.new
# Set the list to users in BodyWrapper
body_wrapper.users = users
# Get instance of UsersOperations Class
uo = Users::UsersOperations.new
# Call update_users method that takes BodyWrapper instance as parameter
response = uo.update_users(body_wrapper)

users = []
# Get instance of Role Class
role = Roles::Role.new
# Set ID to Role instance
role.id = 3_524_033_000_000_026_005
# Get instance of Profile Class
profile = Profiles::Profile.new
# Set ID to Profile instance
profile.id = 3_524_033_000_000_026_011
# Get instance of User Class
user = Users::User.new
# set instance of Profile Class to User
user.profile = profile
# set instance of Role Class to User
user.role = role
user.first_name = '1'
# Set ID to User instance
user.last_name = '1'
user.email = '1@zoho.com'
users.push(user)
# Get instance of BodyWrapper Class that will contain the request body
body_wrapper = Users::BodyWrapper.new
# Set the list to users in BodyWrapper
body_wrapper.users = users
# Get instance of UsersOperations Class
uo = Users::UsersOperations.new
# Call update_user method that takes BodyWrapper instance and user_id as parameters
response = uo.update_user(user_id,body_wrapper)
Copiedclass UpdateUser

    def execute
        url = URI( "https://www.zohoapis.com/crm/v2/users")
        req = Net::HTTP::Put.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["last_name"] = "sadasd";
        user_object["id"] = "3453453553";
        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

UpdateUser.new.execute
1.0.0ES6
Copied//Get instance of UsersOperations Class
let usersOperations = new ZCRM.User.Operations();
//Get instance of BodyWrapper Class that will contain the request body
let request = new ZCRM.User.Model.BodyWrapper();
//Array to hold User instances
let userArray = [];
//Get instance of User Class
let user = new ZCRM.User.Model.User();
//Set ID to User instance
user.setId(34770617304002n);
//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");
//Add User instance to array
userArray.push(user);
//Get instance of User Class
user = new ZCRM.User.Model.User();
//Set ID to Role instance
user.setId(3409643302042n);
role = new ZCRM.Role.Model.Role();
//Set ID to Role instance
role.setId(340964326008n);
//Set role instance to role in User
user.setRole(role);
//Add User instance to array
userArray.push(user);
//Set the array to users in BodyWrapper
request.setUsers(userArray);
//Call updateUsers method that takes BodyWrapper instance as parameter
let response = await usersOperations.updateUsers(request);
Copiedvar listener = 0;
class UpdateUser {

	async updateUsers()	{
		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 UpdateUser().getToken(token)
        headers.set("Authorization", "Zoho-oauthtoken " + accesstoken)
        var requestMethod = "PUT"
        var reqBody = {"users":[
            {
                "id":"35240336089006",
                "first_name":"Patricia"
            }
            ]}
        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 UpdateUser().makeAPICall(requestObj);
        console.log(result.status)
        console.log(result.response)
    }

	async updateSingleUser()	{
		var url = "https://www.zohoapis.com/crm/v2/users/35240336182001"
        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 UpdateUser().getToken(token)
        headers.set("Authorization", "Zoho-oauthtoken " + accesstoken)
        var requestMethod = "PUT"
        var reqBody =  {"users":[
			{
				"first_name":"Patricia"
			}
		]}
        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 UpdateUser().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("id", "692969000000282009");
user1.put("last_name", "B");

users_list = List();
users_list.add(user1);

params = Map();
params.put("users", users_list);

response = invokeurl
[
	url: "https://www.zohoapis.com/crm/v2/users"
	type: PUT
	parameters: params.toString()
	connection:"crm_connection"
];
info response ;

In the request, "@updateuser.json" contains the sample input data.

Request JSON
  • idstring, mandatory

    Specify the record ID of the user you want to update.

Note
  • You can also pass the record ID in the request. Example: {{api-domain}}/crm/v2/users/{{record_id}}

  • Refer to Get User API to obtain the record ID of the user.

  • You cannot update a deactivated user.

  • You cannot deactivate the primary contact of your organization. To deactivate the primary contact, you must assign another user as the new primary contact of your organization and then deactivate the old primary contact.

  • To activate or deactivate a user, use the key status in the input with the value as either active or inactive, respectively.

  • You cannot change the time zone of another user. You can only change the time zone of your own user record. Refer to Fields Metadata API to know the values of the key "time_zone".

  • 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).

  • Refer to Add Records API to know about the field types and their limitations.

Sample Input

Copied{
  "users": [
    {
      "id": "554023000000691003",
      "phone": "123456789",
      "email": "newtocrm@zoho.com",
      "dob": "1990-12-31",
      "role":"79234000000031154",
      "profile":"79234000000031157",
      "country_locale": "en_US",
      "time_format": "HH:mm",
      "time_zone": "US/Samoa",
      "status": "active"
    }
  ]
}

Possible Errors

  • INVALID_DATAHTTP 400

    Cannot update the time_zone of another user
    Resolution: You cannot update the time zone of another user.

  • AUTHORIZATION_FAILEDHTTP 400

    Either trial has expired or user does not have sufficient privilege to perform this action
    Resolution: Contact your system administrator.

  • INTERNAL_ERRORHTTP 400

    Error occurred while updating CRMPlus User in CRM Account
    Resolution: You cannot update a CRM Plus user from your CRM account.

  • INVALID_DATAHTTP 400

    Invalid data
    Resolution: The input you have specified is invalid

  • INVALID_DATAHTTP 400

    Invalid data
    Resolution: Unclosed Script tags found in signature. Specify valid script tags

  • CANNOT_UPDATE_DELETED_USERHTTP 400

    Deleted user cannot be updated
    Resolution: You cannot update a deleted user.

  • INVALID_REQUESTHTTP 400

    Re-invite is not allowed for a confirmed user
    Resolution: You cannot re-invite a confirmed user.

  • EMAIL_UPDATE_NOT_ALLOWEDHTTP 400

    Cannot update email of a confirmed CRM User
    Resolution: You cannot update the email of a confirmed user.

  • DUPLICATE_DATAHTTP 400

    User with same email id is already in CRM Plus
    Resolution: You are trying to specify a duplicate value for a unique field. Ensure that you specify unique and valid email IDs for all the users.

  • ID_ALREADY_DEACTIVATEDHTTP 400

    User is already deactivated
    Resolution: The user you are trying to deactivate is already deactivated.

  • INVALID_REQUESTHTTP 400

    Primary Contact cannot be deactivated
    Resolution: You cannot deactivate a primary contact.

  • ID_ALREADY_ACTIVEHTTP 400

    User is already active
    Resolution: The user you are trying to activate is already active.

  • FEATURE_PERMISSIONHTTP 400

    Share among Subordinates Feature is not available
    Resolution: The share among the subordinated feature is not available for your account. Contact your system administrator.

  • AUTHORIZATION_FAILEDHTTP 405

    Profile and Role cannot be Updated by the user
    Resolution: The current user does not have permission to update the profile and role of another user. 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.UPDATE scope. Create a new client with valid scope. Refer to scope section above.

  • NO_PERMISSIONHTTP 403

    Permission denied to update
    Resolution: The user does not have permission to update users. 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.

  • MANDATORY_NOT_FOUNDHTTP 400

    required field not found
    Resolution: You have not specified the unique ID of the user to be updated in your request. Specify the unique ID of the user.

Sample Response

Copied{
  "users": [
    {
      "code": "SUCCESS",
      "details": {
        "id": "554023000000691003"
      },
      "message": "User updated",
      "status": "success"
    }
  ]
}