1

How to create/update customer using REST API in magento2?

I searched a lot on google but not getting any solution for this.

Please help me in this.

1 Answer 1

3

Create new customer

$userData = array("username" => "admin", "password" => "admin123");
$ch = curl_init("http://magento213/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);


$customerData = [
    'customer' => [
        "email" => "[email protected]",
        "firstname" => "John",
        "lastname" => "Doe",
        "storeId" => 1,
        "websiteId" => 1
    ],
    "password" => "Demo1234"
];

$ch = curl_init("http://magento213/index.php/rest/V1/customers");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);

//For update

$customerData = [
    'customer' => [
        'id' => 10,
        "email" => "[email protected]",
        "firstname" => "John2",
        "lastname" => "Doe2",
        "storeId" => 1,
        "websiteId" => 1
    ],
    "password" => "Demo1234"
];

$ch = curl_init("http://magento213/index.php/rest/V1/customers/10");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);

API List

4
  • magento213, should be your url. It's tested M2.1.3.
    – Sohel Rana
    Commented Jan 12, 2017 at 11:13
  • 1
    I used this code for magnto-2 but password is not updating.
    – satya
    Commented Aug 23, 2018 at 6:43
  • @SohelRana Why do I need to put in alll those fields that are not being updated for an update? (I asked this as its own question here magento.stackexchange.com/questions/258640/… Commented Jan 22, 2019 at 14:04
  • @SohelRana Can we create user using magento 2 own endpoints just passing some username and password. Like we get customer using API.
    – Anees
    Commented Nov 24, 2020 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.