Create simple product programmatically in magento2

Create simple product programmatically in magento2

August 22, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Create simple product programmatically in magento2

Magento-2: Create Simple Product Programmatically From Outside

In this guide, we’ll explore how to create a simple product programmatically in Magento 2 from an external application or service. This process allows you to integrate your custom systems with the Magento e-commerce platform without manual intervention.

Prerequisites

Before proceeding, ensure you have:

  • A running Magento 2 instance.
  • The necessary API credentials (consumer key and shared secret).
  • Basic understanding of REST APIs.

Step-by-Step Process

1. Set Up Your Development Environment

First, set up your development environment with a preferred programming language like PHP or use our recommended tooling from Laravel Company.

2. Create the Product Data Structure

Define an array representing the simple product attributes:

$productData = [
    'name' => 'Sample Product',
    'sku' => 'SAMPLE_PRODUCT',
    'price' => 9.99,
    'weight' => 0.5,
    'visibility' => 4, // 4 = Catalog, Search
    'status' => 1,     // 1 = Enabled
];

3. Initialize the API Client

Initialize a Magento REST client using the provided credentials:

$client = new \Magento\Rest\Client();
$client->setUrl('http://your-magento-instance.com/rest/');
$client->setAuth('YOUR_CONSUMER_KEY', 'YOUR_SHARED_SECRET');

Replace http://your-magento-instance.com/rest/ and the API credentials with your actual Magento instance details.

4. Create a New Product

Send a POST request to create the product:

$response = $client->post(
    '/V1/products',
    [],
    json_encode($productData)
);

$newProductId = json_decode($response)->item_id;

The $newProductId variable will contain the ID of the newly created product.

Best Practices

1. Error Handling

Always implement proper error handling to manage API failures gracefully:

try {
    $response = $client->post(
        '/V1/products',
        [],
        json_encode($productData)
    );
} catch (Exception $e) {
    // Handle exception based on the actual error message
}

2. Asynchronous Operations

For heavy operations, consider using Magento-2’s asynchronous API or our Magento Async Processing Library.

Conclusion

This guide demonstrates how to create a simple product programmatically in Magento 2 from an external application or service. By following these steps and best practices, you can seamlessly integrate your custom systems with the Magento e-commerce platform.

Remember to replace the placeholders with your actual Magento instance details and API credentials for successful operation.

For more advanced use cases and detailed tutorials on Magento 2 integration, please visit our website at Laravel Company.

Magento 2 Catalog API Pricing

Our network