Giter VIP home page Giter VIP logo

wc-api-python's Introduction

WooCommerce API - Python Client

A Python wrapper for the WooCommerce REST API. Easily interact with the WooCommerce REST API using this library.

https://github.com/woocommerce/wc-api-python/actions/workflows/ci.yml/badge.svg?branch=trunk

Installation

pip install woocommerce

Getting started

Generate API credentials (Consumer Key & Consumer Secret) following this instructions http://woocommerce.github.io/woocommerce-rest-api-docs/#rest-api-keys.

Check out the WooCommerce API endpoints and data that can be manipulated in http://woocommerce.github.io/woocommerce-rest-api-docs/.

Setup

from woocommerce import API

wcapi = API(
    url="http://example.com",
    consumer_key="ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    consumer_secret="cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    version="wc/v3"
)

Options

Option Type Required Description
url string yes Your Store URL, example: http://woo.dev/
consumer_key string yes Your API consumer key
consumer_secret string yes Your API consumer secret
version string no API version, default is wc/v3
timeout integer no Connection timeout, default is 5
verify_ssl bool no Verify SSL when connect, use this option as False when need to test with self-signed certificates
query_string_auth bool no Force Basic Authentication as query string when True and using under HTTPS, default is False
user_agent string no Set a custom User-Agent, default is WooCommerce-Python-REST-API/3.0.0
oauth_timestamp integer no Custom timestamp for requests made with oAuth1.0a
wp_api bool no Set to False in order to use the legacy WooCommerce API (deprecated)

Methods

Params Type Description
endpoint string WooCommerce API endpoint, example: customers or order/12
data dictionary Data that will be converted to JSON
**kwargs dictionary Accepts params, also other Requests arguments

GET

  • .get(endpoint, **kwargs)

POST

  • .post(endpoint, data, **kwargs)

PUT

  • .put(endpoint, data), **kwargs

DELETE

  • .delete(endpoint, **kwargs)

OPTIONS

  • .options(endpoint, **kwargs)

Response

All methods will return Response object.

Example of returned data:

>>> r = wcapi.get("products")
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=UTF-8'
>>> r.encoding
'UTF-8'
>>> r.text
u'{"products":[{"title":"Flying Ninja","id":70,...' // Json text
>>> r.json()
{u'products': [{u'sold_individually': False,... // Dictionary data

Request with params example

from woocommerce import API

wcapi = API(
    url="http://example.com",
    consumer_key="ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    consumer_secret="cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    version="wc/v3"
)

# Force delete example.
print(wcapi.delete("products/100", params={"force": True}).json())

# Query example.
print(wcapi.get("products", params={"per_page": 20}).json())

Changelog

See CHANGELOG.md.

wc-api-python's People

Contributors

claudiosanches avatar djiit avatar evert-arends avatar gedex avatar minisu avatar norbert-sebok avatar timjen3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wc-api-python's Issues

Can't use OAuth (API calls over HTTP)

Hi,

Tested with versions 1.0.1 and 1.0.2, I can't use this library over HTTP. It seems to be related to the OAuth signature generated by the OAuth class.

Here is my code (adapted from the README example) :

wcapi = API(
    url="http://0.0.0.0:8080",
    consumer_key=WC_API_KEY,
    consumer_secret=WC_API_SECRET,
    version="v2",
    verify_ssl=False
)

r = wcapi.get("products")

print(r.status_code)
print(r.text)

Here is the return :

401
{'errors': [{'code': 'woocommerce_api_authentication_error', 'message': 'Signature invalide - la signature fournie ne correspond pas'}]}

(I'm using a French translation of WooCommerce)

Do I need to force the use of OAuth1 somewhere ?

Thanks for your help

REST API does not return Product custom fields - Product Properties

We have custom fields added to our products under WooCommerce > Custom Fields > Product Properties. When I do a get request on a product with those properties such as:

r = api.get("products/37")
or r = wcapi.get("products/37?filter[meta]=true")

The JSON returned does not include these custom fields or their values.

How can I retrieve these Product custom fields by the API?

Json format changed

I have been using the API successfully to integrate Categories and Products with existing legacy systems a couple of weeks ago. Developed everything and now it is time to test in the production environment. While in Dvmt environment each time I executed

r = wcapi.get("products/categories?per_page=100")
vWooJason = json.loads(r.text)

the Json generated was like (reduced attributed for simplicity)
[
{ "id":788,
"name":"Name1" },
{ "id":789,
"name":"Name2" },
{ "id":790,
"name":"NameN" }
]

therefore pagination and len(vWooJason) works fine.

Now without changing anything except installing WP-REST-API plugin on WordPress after executing

r = wcapi.get("products/categories?per_page=100")
vWooJason = json.loads(r.text)

the Json generated is

{
"product_categories":[
{ "id":788,
"name":"Name1" },
{ "id":789,
"name":"Name2" },
{ "id":790,
"name":"NameN" }
}

therefore pagination does not work in the same way and len(vWooJason) = 1 instad of the total number of categories.

Questions
a) Any idea of why the format of the Json changed?
b) Any idea on how to return to the original behaviour?

Regards,
Mariano

Docker container crashes occasionally

Running a wcapi.put("orders/12345", data).json() occasionally (about 2% of the time) causes my docker container to crash. data is always an order status change. Running Python 3.6.10

400 errors after updating to Wordpress 4.7

Latest WooCommerce and now the latest WordPress. Everything worked fine (last night) before update this morning.

curl https://example.com/wp-json/wc/v1/products/9522 -u key:secret

works fine, it gives the product info. Log on the server side (Apache) is "GET /wp-json/wc/v1/products/9522 HTTP/1.1" 200 6484 "-" "curl/7.47.0"

When using the following python it doesn't work.

from woocommerce import API
wcapi = API(
                url="https://example.com",
                consumer_key="key",
                consumer_secret="secret",
                wp_api=True,
                version="wc/v1"
        )
print(wcapi.get("products/9522").json())

Result: {'data': {'json_error_code': 4, 'json_error_message': 'Syntax error', 'status': 400}, 'code': 'rest_invalid_json', 'message': 'Invalid JSON body passed.'}

Server log: "GET /wp-json/wc/v1/products/9522 HTTP/1.1" 400 4742 "-" "WooCommerce API Client-Python/1.2.0"

I made no changes to code, simply updated WordPress from 4.6 to 4.7

Base64-Authentication Support

Hey there, i really like the python API that you created!

I am using a development environment that i protect using base64 Authentication in nginx on the / path, so only few people can see the contents of my woocommerce instance.
I think it would be a cool thing to support base64 authentication in the wcapi constructor, so developers can also use the API against a protected environment.

What do you think?
Keep up the good work! ;)

put meta_data not work

I'm trying to update the meta_data of a wordpress producd.

wcapi.put("products/9",{'product':{'meta_data': [{'fifu_image_url':'https://mi-image.png'}] }})

it does not show any errors in the console but it does not update the wp_postmeta table either

Invalid Signature - provided signature does not match

Hi,

I am getting an invalid signature exception (400) using the Setup for the old WooCommerce API v3 example in the documentation (getting a 404 with the P REST API, but that's a separate issue).

I read up on all related issues & solutions regarding woothemes API I could find , but I am not able to figure out what is going wrong. Any pointers?

. {"errors":[{"code":"woocommerce_api_authentication_error","message":"Invalid Signature - provided signature does not match"}]}

string_to_sign =
GET&http%3A%2F%2Fdigitalsystems4dev.com%2Fwc-api%2Fv3%2Fproducts&oauth_consumer_key%_%26oauth_nonce%_%26oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1463680922

query_string = oauth_consumer_key=c***&oauth_timestamp=1463683292&oauth_nonce=750657abcf2e03a85fd1acfb965d806be291daca&oauth_signature_method=HMAC-SHA256&oauth_signature=UKdq5Vm0YDTmZ2LtnKj2%2F%2FIrrYRj3MCRytJt0VQ7ZZ4%3D

URL
http://digitalsystems4dev.com/wc-api/wc/v3/products?oauth_consumer_key=ck_8d60fb00cc4c1a7da8df182c01f6aaa24eabb423&oauth_timestamp=1463683474&oauth_nonce=cbb609be40c3eb5a0d99213d3a79cd3559ffade7&oauth_signature_method=HMAC-SHA256&oauth_signature=idndeHBygNPp2KMVQpedb6SkDJ8PB4UHWLKlbhr8wiI%3D

Why can't delete products?

The code for deleting products seems to be very simple:
from woocommerce import API wcapi = API( url="https://pentaculo.programamos.pt", consumer_key="ck_", consumer_secret="cs_", version="wc/v3", timeout=30 ) print(wcapi.delete("products/109?force=true").json())
But get error:
Traceback (most recent call last): File "C:\Users\ASUS PC\AppData\Local\Programs\Python\Python36\loja.py", line 19, in <module> print(wcapi.delete("products/109?force=true").json()) File "C:\Users\ASUS PC\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\models.py", line 897, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\ASUS PC\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\ASUS PC\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\ASUS PC\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Any help about this?
the code
print(wcapi.get("products").json())
works fine but I can't update a product either
data = { "regular_price": "24.54" } print(wcapi.put("products/109", data).json())
If I access to https://pentaculo.programamos.pt/wp-json/wc/v3/products
got
{"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}

List Orders params does not support ISO compliant date without time

When making a request to the orders endpoint, I found that some params (after and before) which are supposed to take an ISO8601 compliant date do not run unless the user also includes the time.

The error occurs when I run the following command:

resp = wcapi.get("orders", params = {"per_page" : "100", "page" : 1, "after" : "2020-07-31"})
resp.content

with this error returned to the user in resp.content

(b'{"code":"rest_invalid_param","message":"Invalid parameter(s): after","data":'
 b'{"status":400,"params":{"after":"Invalid date."}}}')

But I am able to get a valid response by extending the date to also include time:

resp = wcapi.get("orders", params = {"per_page" : "100", "page" : 1, "after" : "2020-07-31T23:23:59"})

Sorry, you are not allowed to create resources.

Hi,

Having a bit of an issue.

wcapi = API(
    url="http://website.com/",
    consumer_key="ck_XXX",
    consumer_secret="cs_XXX",
    wp_api=True,
    version="wc/v1"
)

woo_post_data = {...}

print(wcapi.post("products", woo_post_data).json())

{u'message': u'Sorry, you are not allowed to create resources.', u'code': u'woocommerce_rest_cannot_create', u'data': {u'status': 401}}

Using latest woocommerce & wordpress and latest wrapper.

It's over http and I've tried via cURL as well, as you've mentioned in a previous issue.

curl -k -u consumer_key:consumer_secret https://www.example.com/wp-json/wc/v1/orders
curl -k -g "https://www.example.com/wp-json/wc/v1/orders?consumer_key=123&consumer_secret=abc"

^ and got the same response.

API(
    url="https://kashalife.net/",
    consumer_key="ck_16c59a1a0693c2723928830da52a30640c2311fd",
    consumer_secret="cs_0b4e0f17741e024b31d0ef799257b972db473305",
    wp_api=False,
    verify_ssl=False,
    version="v3",
    query_string_auth=True
)

^ Tried that:

{u'errors': [{u'message': u'oauth_consumer_key parameter is missing', u'code': u'woocommerce_api_authentication_error'}]}

Any suggestions?

Hope to hear from you soon,

Thank you.

Generating the authentication endpoint, popup not appearing

I am trying to create the automate authentication endpoint for my app, it seems to work fine in terms of the post request to create it but the pop-up where i would connect to/accept the app does not appear, under which url does this popup usually present itself? - the request returns 200 and css/html that seems on point with what i would expect to be the popup... just cant find the actual popup itself when logging in to my woocommerce account..anyone?

verify_ssl=False is being ingnore while uploading images from/to same server

While partially working it helps with errors like:
'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1122)')))

sadly as soon as I try to create product:
wcapi.post("products", data=json_data)

It throw error:

{"code":"woocommerce_product_image_upload_error","message":"Error getting remote image https:\/\/debian.local\/wp-content\/uploads\/2021\/01\/0_img-cache-39.jpg. Error: cURL error 60: SSL certificate problem: self signed certificate","data":{"status":400}}

When src url is pointing on same self-sign server there is error, to workaround it you could replace https to http in image urls.

Any chance to passthru the verify_ssl parameter to curl ?

error in orders API

Sometimes when pulling orders from more then two months ago, sometimes the end of the list of orders looks like:

[actual orders ...
'code',
'message',
'data',
'additional_errors']

It's as if the order database can't pull the furthest-back orders properly. Do you know what might be causing this? I haven't seen any documentation that mentions this type of output.

No route was found matching the URL and request method

Very simple test doesn't seem to be working.

import sys
from woocommerce import API

wcapi = API(
url="https://",
consumer_key="ck_blahblahblah",
consumer_secret="cs_blahblahblah",
wp_api=True,
version="wc/v1"
)
print(wcapi.get("products").json())

returns {u'message': u'No route was found matching the URL and request method', u'code': u'rest_no_route', u'data': {u'status': 404}}

However, when run the following command I get a good return:
curl "https:///wc-api/v3/products?consumer_key=ck_blahblahblah&consumer_secret=cs_blahblahblah&wp_api=True&version=wc/v2&search=ATIGFX45GI"

Clarify 3-leg oauth setup

In my past experience key&secret need to be turned into tokens, i am under the impression that the api handles that, is it true?

I ask because I can't hit any protected endpoints.

	def __init__(self, url, key, secret):
		self.wpapi = API(
		    url=url,
		    consumer_key=key,
		    consumer_secret=secret,
		    api="wp-json",
		    version="wp/v2"
		)
		print "API initialized to website: " + url
...
	def update_product(self, payload):
		path = "posts/" + str(payload['id'])
		r = self.wpapi.post(path,payload)
		print r.status_code
		print r.text
AssertionError: API call to https://mysire/wp-json/wp/v2/posts/64 returned 
CODE: 401
<html>
 <body>
  <p>
   {"code":"rest_cannot_edit","message":"Sorry, you are not allowed to edit this post.","data":{"status":401}}
  </p>
 </body>
</html> 
HEADERS: {'X-Robots-Tag': 'noindex', 'X-Content-Type-Options': 'nosniff', 'Access-Control-Expose-Headers': 'X-WP-Total, X-WP-TotalPages', 'Transfer-Encoding': 'chunked', 'Keep-Alive': 'timeout=2, max=99', 'Server': 'Apache', 'Connection': 'Keep-Alive', 'Link': '<https://mysite/wp-json/>; rel="https://api.w.org/"', 'Allow': 'GET', 'Date': 'Wed, 02 Aug 2017 23:52:42 GMT', 'Access-Control-Allow-Headers': 'Authorization, Content-Type', 'Content-Type': 'application/json; charset=UTF-8'}

Problem with updating backorders and stock_status

This problem does not happen when using cURL to send the same data!

We are currently reimplementing the stock syncing, since now we can get data from our b2b seller about their availability. When updating stock, I send "stock_quantity", "stock_status" and "backorders" (when needed). While the "stock_quantity" is updated, the other two parameters aren't.

This is an example of data, that gets sent via PUT request.
{"stock_quantity": 25, "stock_status": "instock"}
{"stock_quantity": 0, "stock_status": "onbackorder", "backorders": "notify"}
{"stock_quantity": 0, "stock_status": "outofstock", "backorders": "no"}

It connects to the store without a problem, since fetching the products or updating the price works. We are not using any plugins that would interact with WooCommerce stocks. The version we are using is "wc/v3".

timestamp error

Hello,

I have this error code :
{'code': 'woocommerce_rest_authentication_error', 'data': {'status': 401}, 'message': 'Invalid timestamp.'}

I am sure it's the right keys and url because I run the code on the same server where the wordpress is installed andd it works.
But when I run this code from my personal computer, I constantly have the error with the timestamp.

And I'm using this
wcapi = API(
url="url",
consumer_key="xxxx",
consumer_secret="xx",
wp_api=True,
version="wc/v1"
)

Thanks

Performing pagination

This might not be the right place, but I'm wondering how to perform pagination with the python wrapper for woocommerce

Not working anymore

Hello,

As of a few months this module does not seem to work anymore, I found the culprit, as it seems to work when I include this header:
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0'. This explains why CURL works, but python requests not anymore.

Best regards,

Evert

How to speed up the response after calling Woocommerce APIs?

I have an issue with the speed of the Woocommerce REST API. What I’m trying to do is import about 10k products (~65k variations) in total as fast as possible. The issue I’m running into is it seems that WordPress loads core, plugins and themes when the REST API is called.

GET Product/Categories

While trying to get all product/Categories from Woocommerce I am only getting a few instead of the 500 Categories that I have created programmatically. Any advice?

I am executing the follow code from Python
"...
wcapi = API(
url="http://99.99.99.99",
consumer_key="ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
consumer_secret="cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
wp_api=True,
version="wc/v1"
)
r = wcapi.get("products/categories/")
r.json()
..."

Have seen that there is a parameter called "per_page" to determine the maximum number of items to be returned in result set. How should I apply in the code above?

Regards,
Mariano

Get product ID from SKU

I've already tried wcapi.get('products?filter[sku]="{MY_SKU}'), but it returns a list with the top 10 products in my ecommerce.

wcapi.get('orders') returns 403

I connect to my WooCommerce webshop through the WooCommerce REST API Python wrapper,

I.e,

from woocommerce import API

wcapi = API(
    url="https://mywebshop.whatever",
    consumer_key="ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    consumer_secret="cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    wp_api=True,
    version="wc/v1"
)

API has read/write access.

All worked fine for months up to yesterday.


Problem

Since yesterday latest_order = wcapi.get('orders').json() returns a JSONDecodeError: Expecting value. Also, wcapi.get('orders') returns a <Response [403]>.

I don't know what's causing this all of a sudden and I'm not sure how to solve it either.

JSONDecodeError

Sometimes when when i want to get response in json format:
r.json()

i get this error:
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)

what could be the problem? is there any way to fix this?

per_page and all integer parameters does't works

While trying to get product/categories from Woocommerce I got this error:
"per_page is not of type integer"

my code:

wcapi = API(
url="http://my_web.site",
consumer_key="ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
consumer_secret="cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
version="wc/v3"
)

categories = wcapi.get("products/categories/?per_page=1").json()

get the same error for all integer parameters

Download all products in specific language (WPML)

My WooCommerce has 3 different languages: default lang is French.

wcapi.get('products/?per_page=100').json()

gives up to 100 products in the default language.

wcapi.get('products/?lang=en').json()

gives up to 10 products in the English language.

How do I combine to two, such that I get up to 100 products in the English language?

How do I get order details by order number not by order id [woocommerce-rest-api] [python]

I am trying to get the order details through the woocommerce-rest-api with the order number (in JSON response field 'number') instead of the order id. How can I archieve this?

As I understood it wcapi.get("orders?number=JZ-31") should work, but I get several orders instead of the one with the number "JZ-31" ("JZ-31" is included in the response as many others also). I guess it's interpreted as wcapi.get("orders"). That's why I get several order instead of the specific one. With the ID it works without problems, but I want it with the order number.

wcapi.get("orders?number=JZ-31") # Did not work
wcapi.get("orders", params={"number" : "JZ-31"}) # Did not work

I expect that I get a response with containing exactly one order with the order number I pass. But I am actually getting all orders. As I said if I use the order id it's working without problems but I need to get the orders by the order number.

Can't delete categories - 'force': 'true? is not of type boolean'

There might be an issue with the delete method or anything related to the rest code.
Here is the error message when I try to delete a category :

{
  'code': 'rest_invalid_param', 
  'message': 'Invalid parameter(s): force', 'data': {
    'status': 400, 
    'params': {
      'force': 'true? is not of type boolean.'
      }
  }
}

and my code (tried few variations) :

wcapi.delete("products/categories/19?force=true).json()
wcapi.delete("products/categories/19).json()

Please help!

Issue with authentication consumer key or consumer secret invalid

I'm creating credentials using the endpoint /wc-auth/v1/authorize with scope=read_write most times the consumer key and secret that I get are valid, but a couple of times I get consumer key or consumer secrets that are invalid when I try to use them later in code like this:

wcapi = API(
    url=  shop_url,
    consumer_key= key,
    consumer_secret= secret
)
response = wcapi.get("orders?page=1")
# Then response.text is {"errors":[{"code":"woocommerce_api_authentication_error","message":"Consumer Secret is invalid"}]}
#  or {"errors":[{"code":"woocommerce_api_authentication_error","message":"Consumer Key is invalid"}]}

Has this issue been detected yet? Is it related to the python wrapper or woocommerce plugin?

wp_api=True constructs invalid path to endpoint

When constructing the API class, passing wp_api=True adds "wc-jason" to the path which is incorrect:
https://kashalife-beta.com/**wp-json/**v3/products

wcapi = API(
url="https://domain.com/",
consumer_key="ck_9e374df9cbd431466d0ff",
consumer_secret="cs_fb0dbeb028e0ef76c",
wp_api=True,
version="v3",
)

According to the http://woothemes.github.io/woocommerce-rest-api-docs/#schema the correct endpoint is https://www.your-store.com/wc-api/v3

Commenting the below out in def __get_url(self, endpoint) fixes the issue:
#if self.wp_api:
#api = "wp-json"

Woocommcerce REST API URLs not working

From one moment to another i could see the Json data of the site im workning on, to use it on an android app, when its writen with the domain name of the ssl certificate it appears this { code: "woocommerce_rest_cannot_view", message: "Sorry, you cannot list resources.", data: { status: 401 } }

but when i use the ip adress instead, it works fine but it seems the site is not secured,
when i try to authenticate it apears this error: "An error occurred in the request and at the time were unable to send the consumer data"
its neede for this to be ready as soon, how can i solve this, thanks a lot

Product categories with backslashes in the title don't show up in API search results

Category name = 'Система Linux \Unix'
wcapi.get("products/categories?search=%s" % ('Система Linux \Unix')).json()
not return existed result
Escaping u'Система Linux \Unix' not return existed result,
urllib.quote_plus(u'Система Linux \Unix') not return existed result
quote(u'Система Linux \Unix') not return existed result

Also problem if name of category with forward slash, example category name: '/n software' and if ampersand in category name, example: 'Tools&Comps'

User-Agent

I need to change a User-Agent for specific reasons, please add User-Agent as a optional parameter to API.

Download all Products

First thank you very much for this amazing work!!

I am trying to get all the products and I don' really know how to do it.

I have tried to do

wcapi.get('products?per_page=100')
But I have more than 100 products

Furthermore, I have tried to introduce the pagination as it is recommended in the manual, but it does not say how to introduce it in the code...

I would love if someone could help me out with this.

Yours sincerely,

woocommerce_api_authentication_error","message":"Consumer Secret is invalid

When using HTTPS in the API URL parameter below the authentication fails with the error"

"woocommerce_api_authentication_error","message":"Consumer Secret is invalid".

HTTP works fine.

Questions:

  • Any suggestions on how to troubleshoot this?
  • If this is a potential server side configuration issues, do you have any pointers on how to configure it correctly?
  • Could you give me an example of how to use query parameters instead? The WooCommerce REST API documentation hints at an example for servers that not properly parse the Authorization header, but it is actually missing.
API(
            url="https://kashalife.net/",
            consumer_key   ="ck_16c59a1a0693c2723928830da52a30640c2311fd",
            consumer_secret="cs_0b4e0f17741e024b31d0ef799257b972db473305",
            wp_api=False,
            verify_ssl=False,
            version="v3",
        )

Thanks - Christoph

not get all products

the next code
`
import json
from woocommerce import API

wcapi = API(
url="xxxxxxxxxxxxx",
consumer_key="xxxxxxxxxxxx",
consumer_secret="xxxxxxxxxxxx"
)

r = wcapi.get("products")
print r.text
`

just get 10 products, and where are the others? o.O

REST authentication error

Hello,

Having truble authenticating with rest api, all the time I get the same error.

Wordpress 4.7.4
Woocommerce 3.0.5
Python 2.7.13

from woocommerce import API

wcapi = API(
    url="http://XYZ/~aclassi2/note/",
    consumer_key="ck_YYY",
    consumer_secret="cs_XXX",
    wp_api=True,
    version="wc/v2",
    verify_ssl=False,
    query_string_auth=True
)

{"code":"woocommerce_rest_authentication_error","message":"Invalid signature - provided signature does not match.","data":{"status":401}}

When I use Postman, it works fine. I also tested with nodeJS, is maybe python lib broken?

Fetching endpoint returns old data

When doing a get request on, for example 'wc/v3/products/3895/variations/3899'

It returns old data. When doing the same request using, for example, postman, i get the newest version/

Postman result:
"id": 3899, "date_created": "2020-05-16T12:21:21", "date_created_gmt": "2020-05-16T12:21:21", "date_modified": "2020-05-16T13:51:46", "date_modified_gmt": "2020-05-16T13:51:46", "description": "",

Python result:
'id': 3899, 'date_created': '2020-05-16T12:21:21', 'date_created_gmt': '2020-05-16T12:21:21', 'date_modified': '2020-05-16T12:32:35', 'date_modified_gmt': '2020-05-16T12:32:35', 'description': ''

Invalid Signature for multiple filter parameters

I get 401 status code and this error if I try to use more than one filter parameters:

{u'errors': [{u'message': u'Invalid Signature - provided signature does not match', u'code': u'woocommerce_api_authentication_error'}]}

I'm using v3.

One parameter works well:

api.get('orders?filter[limit]=1000')
api.get('orders?filter[created_at_min]=2015-01-03')

But there is an Invalid Signature error for multiple filter params:

api.get('orders?filter[limit]=1000&filter[created_at_min]=2015-01-03')

The example from the REST API docs is failing too:

api.get('orders?status=completed&filter[created_at_min]=2013-11-01&filter[created_at_max]=2013-11-30')

Am I doing something wrong? Or is there a bug in the generate_oauth_signature method?

Timeout exception yet uploaded the data

I am having a weird issue. I am using API for a Woocommerce setup on my local machine. Onr running I am getting the exceptions:

Traceback (most recent call last):
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
    httplib_response = conn.getresponse()
  File "/Users/Me/Data/anaconda3/lib/python3.7/http/client.py", line 1321, in getresponse
    response.begin()
  File "/Users/Me/Data/anaconda3/lib/python3.7/http/client.py", line 296, in begin
    version, status, reason = self._read_status()
  File "/Users/Me/Data/anaconda3/lib/python3.7/http/client.py", line 257, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/Users/Me/Data/anaconda3/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/util/retry.py", line 368, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/packages/six.py", line 686, in reraise
    raise value
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 386, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 306, in _raise_timeout
    raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='localhost', port=80): Read timed out. (read timeout=5)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Me/Data/Business/NisaaPK/data_uploader_api/uploader.py", line 48, in <module>
    add_product(wcapi)
  File "/Users/Me/Data/Business/NisaaPK/data_uploader_api/uploader.py", line 31, in add_product
    print(wc.post("products", data))
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/woocommerce/api.py", line 112, in post
    return self.__request("POST", endpoint, data, **kwargs)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/woocommerce/api.py", line 103, in __request
    **kwargs
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/requests/api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/Users/Me/Data/anaconda3/lib/python3.7/site-packages/requests/adapters.py", line 529, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='localhost', port=80): Read timed out. (read timeout=5)

When I checked on the site the product was there! This is the code I am using:

from woocommerce import API


def add_product(wc):
    data = {
        "name": "Sample Product",
        "type": "simple",
        "regular_price": "1221.99",
        "sale_price": "921.99",
        "description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
        "short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
        "categories": [
            {
                "id": 135
            },
        ],
        "tags": [

        ],
        "button_text": "Visit here to buy",
        "images": [
            {
                "src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg"
            },
            {
                "src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg"
            }
        ],
        "external_url": 'http://adnansiddiqi.me'
    }
    print(wc.post("products", data))


if __name__ == '__main__':
    KEY = 'XXX'
    SECRET = 'XXX'

    wcapi = API(
        url="http://localhost/shop.ab/",
        consumer_key=KEY,
        consumer_secret=SECRET,
        version="wc/v3"
    )

    # r = wcapi.get("products")
    # products = r.json()
    # print(len(products))
    add_product(wcapi)

getting an import error.

after doing the pip install WooCommerce and placing the

from woocommerce import API

test = API(values here)

running this shows this below.

from woocommerce import API
ImportError: cannot import name 'API'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.