WooCommerce REST API – Import products from JSON

I had a task to create a PHP script to import simple and variable products from JSON file using the WooCommerce REST API. Thought it might be worth sharing with others because I couldn’t find much information about products import from JSON using the API.

To make it easier to understand, I created a simple JSON file with one simple product and one variable product that have two product variations. You can get all files from Github repository.

products.json

Getting started

What you need to do is download a PHP wrapper for the WooCommerce REST API. You can download it using composer from https://packagist.org/packages/automattic/woocommerce If you don’t have composer yet, then you can download it from https://getcomposer.org

Setup

Setup for the new WP REST API integration (WooCommerce 2.6 or later):

1. Parse JSON

Convert JSON string to PHP array.

2. Get all product attributes from JSON

We need to get all product attributes names and values from JSON file.

3. Get products and variations from JSON for importing

4. Merge products and product variations

Used to loop through products, then loop through product variations.

5. A simple function to print status message

Import products to WooCommerce using the API

You can find the script on Github repository

34 thoughts on “WooCommerce REST API – Import products from JSON”

  1. Thanks for the amazing tutorial. I am beginner in woocommerce. Can you please tell me where to put this set WP REST API integration code

  2. This is a very good tutorial. I am not a programmer and it is very hard when you want to put your wordpress woocommerce store working but your supplier gives you a lot of code to achieve the Token authorization and to import your products. My problem is I am just starting in this json code and logic and I am just understanding the logic of that.

  3. Hi, thank you for the amazing job you did here. Is a fact that there is nothing that can explain how this json files can be used. My supplier gave me all the codes to get the token and after that the products and variations. You say that I have just to create the pho file for the import as you explain and all the products will be upload/update/create woocommerce of my store?

    1. Hi Bruno,

      It depends on the format of your JSON file. This tutorial shows you how you can parse JSON files and with some PHP import them to WooCommerce. Would you like to send me your JSON file so that I can take a closer look and help you more?

  4. How do you add/apply images to these newly created posts? I tried adding image urls to the .json file in the place I thought they should be but nothing ever generated through woocommerce. Any help would be greatly appreciated. Thanks for this awesome tut!

    1. Hi Robert,

      Are you using the REST API to upload the products and images? If so, you need to define ‘images’ URLs when creating a product. See: http://woocommerce.github.io/woocommerce-rest-api-docs/#product-properties and http://dominykasgel.com/wp-content/uploads/2017/09/REST-API-product-images.png . The API includes images generating too. If you don’t use the API, you can upload the images using https://codex.wordpress.org/Function_Reference/wp_insert_attachment, then adding the images IDs to a product https://gist.github.com/zarankumar/f80a73598152edf7d67a8c91dbf3be25 .

      1. Thanks for that info. I actually got that figured out yesterday. It is working great with your code and a few additions to the json file! Thanks again for getting me started in the right direciton.

        Now I’m running into the problem of every time I run the import.php a second time (to do another import) I get this error:

        Error: Slug “size” is already in use. Change it, please. [woocommerce_rest_invalid_product_attribute_slug_already_exists]

        Any idea how to fix this? How can I have the import run multiple times even if a certain attribute exists already (in this case “size”). I could not figure it out in the code. I’m sorry.

        Thanks again for all your help

          1. Hi Tales,

            To get you started in the right direction, I wrote a few lines of code. My code explains how you can import an image to a simple product. Firstly, you need to add “image” to products.json file, then add $product[$key][‘images’][] = array( ‘src’ => (string) $pre_product[‘image’], ‘position’ => 0 ); in get_products_and_variations_from_json() function. See my working code example here: https://pastebin.com/c8z4ujja

        1. Hi Tales,

          I’m happy to hear that. If you want to run the import multiple times, then you need to comment out some code between #29 – #69 lines. The API doesn’t allow you to create the same attributes with the same data, so you need to ignore this part. However, in order to assign a product to a certain attribute, you need to pass $added_attributes as a second argument to get_products_and_variations_from_json( $json, $added_attributes ); functions. Solution: Get already added attributes from WooCommerce – http://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-product-attributes See how it’s already done and create the same $added_attributes variable. If you also need to create new attributes during your next import, then don’t ignore the part below // Import Attributes, but just get all product attributes and see if it’s already there if not, then add it.

      2. Also, do you know how I would set images for individual variations? Can I just add it to the json file or will I need to add code to handle that as well? Thanks again for your help.

        1. Hi Robert,

          Yes, just add the images to JSON file. I wrote a few lines of code with an explanation how you can add/import the images for simple products. See my code here: https://pastebin.com/c8z4ujja For variations, you need to follow the same way – have URLs in products.json file, then add the images to your main product and get the images IDs. You can retrieve the product data and image IDs once it’s imported. This line: $wc_product = $woocommerce->post( ‘products’, $product ); When you have the images IDs, then you need to assign them to a variation. Example here: http://woocommerce.github.io/woocommerce-rest-api-docs/#product-variation-properties … For every different case you need to modify the import script.

  5. Hi Dominykas,

    I need to change the way woocommerce works so that instead of getting the product price in the standard way it gets the price that I feed to it via an API. Is there a simpler way of achieving that?

    Thanks!

    1. What I mean is, is it easier to import just the price and integrate it to the existing products or get all the product information from the api?

      Awesome job you did there, by the way 🙂

      1. I’m glad to hear it’s useful! 🙂 It’s better to import and update the prices instead of getting the data from the API for every page load. You may have too many calls and it may slow down your website.

          1. If you just want to show the price, but don’t use it for the checkout, then I don’t see a problem. Otherwise, I would setup a cron job and run a script to update the prices in the database. You can have only one call to the API just to update the prices in the DB and run it daily.

  6. Last question for now I swear! Here’s an even trickier one. How do we add multiple variation types and conjoin them? I know it’s easy to accomplish manually when adding a product but I haven’t quite figured out how to make it work with this code.

    For example I’d like to have this import generate variations based off of two separate types of attributes, in this case Size and Gender.

    I need variations generated for every cross of both attribute types. So like this:
    1. [Small] [Mens]
    2. [Small] [Womens]
    3. [Small] [Youth]
    4. [Medium] [Mens]
    5. [Medium] [Womens]
    6. [Medium] [Youth]

    From the WooCommerce API they provide this in their code:

    “attributes”: [
    {
    “id”: 6,
    “position”: 0,
    “visible”: false,
    “variation”: true,
    “options”: [
    “Black”,
    “Green”
    ]
    },
    {
    “name”: “Size”,
    “position”: 0,
    “visible”: true,
    “variation”: true,
    “options”: [
    “S”,
    “M”
    ]
    }
    ],

    However, when adding this “attributes” to my json file it does not work.

    If you could help me solve this last problem you would be an absolute life saver!!

  7. All else seems to be in place, I got it to add images to the products and product variables as well, thanks!

    I’m having a hard time wrapping my head around this though:
    I’m trying to create a script that updates the prices of my products and their variations via a cron job. I suppose I’d need this API?
    http://woocommerce.github.io/woocommerce-rest-api-docs/?php#batch-update-products

    I’ll have to call the Rest API and update it with the prices of my external API (since they vary wildly during the day I don’t think I’d need to compare them before updating). But, I’m at a loss on how to isolate the price variable and have it updated.

    1. I’m happy to hear that! I think you are looking at the right page. Hmm, could you explain “how to isolate the price variable and have it updated”? Do you want to exclude the main product from updating? I see all parameters are optional except ID. Just tested the price updating for variable product and its variations. My code: https://pastebin.com/zLyYvSmf

      1. Awesome! I guess I was overcomplicating this stuff. I was all tangled up on new API POST authentications and what not. This code seems to be working properly.
        https://pastebin.com/vX28gMy9

        The way it works now, I have to set the prices manually in the script. How would you do to have the script look for the prices on the external API instead?

        1. Hey Tales, I’m glad that you managed to make it work properly! 🙂

          Answering your question, it depends on the data you need. In order to change the price, you need to know the product ID. Can you get it from your external API? If not, then you need some kind of parameter to sync the price from your external API to the right product in your store. It could be SKU or product title. When you have the product id you can change the price.

  8. Hey Dominykas,
    I’ve been banging my head over this and I got this script to work:
    https://pastebin.com/nHdSxgFc

    As you can see, it’s a nightmare if you need to update anything, as each update call is linked to a specific product ID.

    I was trying to update the regular_price based on the SKU, but I can’t get it to work. My api returns the values in this format btw: https://pastebin.com/HsDissxM

    How could one get the SKU and regular_price keys from the API and update the price in the database based on that? I though about something like a foreach loop and an if statement comparing the SKUs and updating the price, but I just can’t pull it off ~.~

  9. Hello,

    Nice tutorial. I getting this error when execute import.php file:
    Fatal error: Class ‘Automattic\WooCommerce\Client’ not found in /

    Should I put the code in Woocommerce template file?

    Thanks

    1. I’m glad to hear that you find the article useful. This means a PHP wrapper for the WooCommerce REST API is missing. There are wrappers for Ruby and Python as well. In order to use the API in PHP, you need to install the wrapper. Take a look at installation: https://github.com/woocommerce/wc-api-php#installation The best way is to use composer (https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx) and install it in the same directory as the import.php file.

Leave a Reply

Your email address will not be published. Required fields are marked *