Python client library for Bigcommerce API

Overview

Bigcommerce API Python Client

Build Status Package Version

Wrapper over the requests library for communicating with the Bigcommerce v2 API.

Install with pip install bigcommerce or easy_install bigcommerce. Tested with python 3.8, and only requires requests and pyjwt.

Usage

Connecting

import bigcommerce

# Public apps (OAuth)
# Access_token is optional, if you don't have one you can use oauth_fetch_token (see below)
api = bigcommerce.api.BigcommerceApi(client_id='', store_hash='', access_token='')

# Private apps (Basic Auth)
api = bigcommerce.api.BigcommerceApi(host='store.mybigcommerce.com', basic_auth=('username', 'api token'))

BigcommerceApi also provides two helper methods for connection with OAuth2:

  • api.oauth_fetch_token(client_secret, code, context, scope, redirect_uri) -- fetches and returns an access token for your application. As a side effect, configures api to be ready for use.
  • BigcommerceApi.oauth_verify_payload(signed_payload, client_secret) -- Returns user data from a signed payload.

Accessing and objects

The api object provides access to each API resource, each of which provides CRUD operations, depending on capabilities of the resource:

api.Products.all()                         # GET /products (returns only a single page of products as a list)
api.Products.iterall()                     # GET /products (autopaging generator that yields all
                                           #                  products from all pages product by product.)
api.Products.get(1)                        # GET /products/1
api.Products.create(name='', type='', ...) # POST /products
api.Products.get(1).update(price='199.90') # PUT /products/1
api.Products.delete_all()                  # DELETE /products
api.Products.get(1).delete()               # DELETE /products/1
api.Products.count()                       # GET /products/count

The client provides full access to subresources, both as independent resources:

api.ProductOptions.get(1)                  # GET /products/1/options
api.ProductOptions.get(1, 2)               # GET /products/1/options/2

And as helper methods on the parent resource:

api.Products.get(1).options()              # GET /products/1/options
api.Products.get(1).options(1)             # GET /products/1/options/1

These subresources implement CRUD methods in exactly the same way as regular resources:

api.Products.get(1).options(1).delete()

Filters

Filters can be applied to all methods as keyword arguments:

customer = api.Customers.all(first_name='John', last_name='Smith')[0]
orders = api.Orders.all(customer_id=customer.id)

Error handling

Minimal validation of data is performed by the client, instead deferring this to the server. A HttpException will be raised for any unusual status code:

  • 3xx status code: RedirectionException
  • 4xx status code: ClientRequestException
  • 5xx status code: ServerException

The low level API

The high level API provided by bigcommerce.api.BigcommerceApi is a wrapper around a lower level api in bigcommerce.connection. This can be accessed through api.connection, and provides helper methods for get/post/put/delete operations.

Accessing V3 API endpoints

Although this library currently only supports high-level modeling for V2 API endpoints, it can be used to access V3 APIs using the OAuthConnection object:

v3client = bigcommerce.connection.OAuthConnection(client_id=client_id,
                                                  store_hash=store_hash,
                                                  access_token=access_token,
                                                  api_path='/stores/{}/v3/{}')
v3client.get('/catalog/products', include_fields='name,sku', limit=5, page=1)

Managing OAuth Rate Limits

You can optionally pass a rate_limiting_management object into bigcommerce.api.BigcommerceApi or bigcommerce.connection.OAuthConnection for automatic rate limiting management, ex:

import bigcommerce

api = bigcommerce.api.BigcommerceApi(client_id='', store_hash='', access_token=''
                                     rate_limiting_management= {'min_requests_remaining':2,
                                                                'wait':True,
                                                                'callback_function':None})

min_requests_remaining will determine the number of requests remaining in the rate limiting window which will invoke the management function

wait determines whether or not we should automatically sleep until the end of the window

callback_function is a function to run when the rate limiting management function fires. It will be invoked after the wait, if enabled.

callback_args is an optional parameter which is a dictionary passed as an argument to the callback function.

For simple applications which run API requests in serial (and aren't interacting with many different stores, or use a separate worker for each store) the simple sleep function may work well enough for most purposes. For more complex applications that may be parallelizing API requests on a given store, it's adviseable to write your own callback function for handling the rate limiting, use a min_requests_remaining higher than your concurrency, and not use the default wait function.

Further documentation

Full documentation of the API is available on the Bigcommerce Developer Portal

To do

  • Automatic enumeration of multiple page responses for subresources.
Comments
  • dependency on streql

    dependency on streql

    The pip install fails to install streql on python 2.7 on Windows7. It complains that it cannot find vcvarsall.bat. I looked through the API and noticed that streql is only imported, but not used in the code. I was able to use the api on Windows7 by removing that line in connection.py. I don't want to have to install microsoft Visual Anything unless I have to.

    opened by jtallieu 12
  • 406 Not Acceptable ({

    406 Not Acceptable ({"error":"Invalid format."}) during api.oauth_fetch_token call

    Expected behavior

    api = bigcommerce.api.BigcommerceApi( client_id=config['bigcommerce'].get('client_id'), store_hash=context, access_token='')

    token = api.oauth_fetch_token( config['bigcommerce'].get('client_secret'), code, context, scope, config['bigcommerce'].get('redirect_uri')) print(token)

    {'access_token': '***', 'scope': '***', 'user':***, 'context': '***'}

    Actual behavior

    Python 3.6.3 bigcommerce==0.18.0

    api = bigcommerce.api.BigcommerceApi( client_id=config['bigcommerce'].get('client_id'), store_hash=context, access_token='')

    token = api.oauth_fetch_token( config['bigcommerce'].get('client_secret'), code, context, scope, config['bigcommerce'].get('redirect_uri'))

    bigcommerce.exception.ClientRequestException: 406 Not Acceptable @ https://login.bigcommerce.com/oauth2/token: b'{"error":"Invalid format."}'

    Steps to reproduce behavior

    Upgrade bigcommerce to 0.18.0 (from the bigcommerce==0.17.3)

    pip install bigcommerce==0.18.0 running in powershell terminal

    opened by Hitoki 11
  • Python API Client overhaul

    Python API Client overhaul

    Decided to update the client, as it wasn't really working.

    Replaced httplib2 with requests and rewrote most of it. Now (should) support everything the API can do. Not tested extensively; is probably buggy as heck.

    opened by bc-jackiehuynh 9
  • iter_all() Automatic Paging

    iter_all() Automatic Paging

    What?

    Main thing is I added automatic paging to the all method of ListableApiResource. With this pull it returns a generator with all of the objects. It does this by requesting pages from the api till it returns a empty list.

    Also cleaned up some warts i found while going thought the code.

    Happy to take a similar approach for ListableApiSubResource resource however I am not sure of the semantics of paging subresources.

    opened by surbas 8
  • Prepare for 0.11.0 release

    Prepare for 0.11.0 release

    • Update package definition in setup.py
    • Update changelog
    • Update license year
    • Switch to Restructured Text for README so we can use the same file for GitHub and PyPi
    • Minor updates in README
    opened by mattolson 7
  • I'm getting a memory address with each request I send.

    I'm getting a memory address with each request I send.

    Every time I send a GET request to pull data from Big Commerce, I get a Memory Address with a python dictionary inside it.

    How can I get just the python dictionary inside it instead?

    opened by filipeteles 5
  • Support for product count operation

    Support for product count operation

    I ended up not using this (and therefore not testing it thoroughly), but I think this takes care of the product counts unless I'm missing something.

    Submitting for your consideration.

    Regards!

    opened by sebaacuna 5
  • Filter and Pagination

    Filter and Pagination

    I was working on this API for a friend, who later told me about this project after I was almost finished. After taking a look, I noticed that iterating over more than 250 resources and filtering were not supported. Please pull if you like where I am heading with this project. Support for updating and creating will be coming soon.

    Thanks,

    opened by jtallieu 5
  • Library is not documented on Bigcommerce Developer Portal

    Library is not documented on Bigcommerce Developer Portal

    Expected behavior

    should be documented at https://developer.bigcommerce.com/ as per https://github.com/bigcommerce/bigcommerce-api-python#further-documentation

    Actual behavior

    no documentation

    Steps to reproduce behavior

    go to https://developer.bigcommerce.com/ there is no documentation for this library.

    opened by sabotagebeats 4
  • Helper method for creating an authorize URL

    Helper method for creating an authorize URL

    Would be nice to have a method that generates the authorize URL

    Also, the developer site doesn't document what the authorize URL is. I had to guess what it is:

    https://login.bigcommerce.com/oauth2/authorize
    
    opened by dasevilla 4
  • Add high level class layer to API

    Add high level class layer to API

    This adds a new layer to the API on top of @bc-jackiehuynh's existing work. The new class-based layer is heavily inspired by the excellent Stripe API (stripe/stripe-python), and in the process we end up melding a lot of Jackie's work with several ideas from the old version of the API.

    Basic examples of usage are available in the README and examples directory. Test coverage is currently very poor, but will improve over time.

    Ping @maetl

    opened by tgsergeant 4
  • Using v3 Catalog/Product filters

    Using v3 Catalog/Product filters

    Expected behavior

    I'm trying to use the v3 Products API's, but I need to filter by "id:not_in". As far as I know, Python does not allow colons in variable names. So what is the work-around to this?

    I expect that all the filters using a colon will not work.

    # v3 products
    include_fields = "sku, price"
    sort = "sku"
    id:not_in = "689"
    endpoint = '/catalog/products'
    response = api.get(endpoint, include_fields=include_fields, id:not_in=id:not_in, limit=5, page=1, sort=sort)
    

    The expected result would be a list of products where the IDs are not in the list of IDs.

    Actual behavior

    id:not_in = "689" NameError: name 'not_in' is not defined

    Steps to reproduce behavior

    Use above filter to reproduce.

    opened by joegarcia 0
  • Zip payment method not returning in API

    Zip payment method not returning in API

    Expected behavior

    Zip should be returned as a payment method in the PaymentMethods API resource when it is enabled.

    Actual behavior

    Zip is not returned as a payment method.

    Steps to reproduce behavior

    1. Enable Zip as a payment method in the store
    2. Connect to API and run api.PaymentMethods.all()
    3. Zip is not returned as one of the enabled payment methods
    opened by emilian 0
  • Getting subresources alongside products (not separately)

    Getting subresources alongside products (not separately)

    The API supports getting subresources within the same request as products:

    image

    However, the client seems to only provide access one at a time via a separate API call.

    image

    There's no way to just request products and subresources in one call?

    opened by dsoprea 1
  • Old releases, broken functions, V3 support

    Old releases, broken functions, V3 support

    The README.md suggests that api.Products.iterall() and api.Products.count() should exist but they do not appear to.

    Also, the releases page says that the last release was 2019. They're haven't been any substantial updates since then?

    Also, the forum entry at https://github.com/bigcommerce/bigcommerce-api-python/issues/59 says the following:

    Hi @sabotagebeats, the pagination values you're referring to come from the V3 BC API, whereas this library is for the older V2 API and has not yet been updated for V3.
    

    Has V3 been since released?

    Lastly, when I call (api).Products.all() for some page equal-to-or-greater-than the page-count (the page after the last page of results), I get a single string with a value of "_connection" back. So, when there are products, we get a Product. Otherwise, we get a string with "_connection". I would expect an empty result or, at worst, a None. Can you explain what's going on here? How is pagination supposed to work? I'm having issues finding documentation and what little documentation is available (above) seems broken or inaccurate. Since the source-code is reflective, there are no clues there, either.

    opened by dsoprea 1
  • Is there a way to update products in batches (more than 1 at a time)?

    Is there a way to update products in batches (more than 1 at a time)?

    Currently, I'm using the following to update information about a single product.

    api.Products.get(1234).update(inventory_level=20)

    Is there a way to update multiple products? I've tried something like this, but got a 404 error.

    api.Products.get([123, 456]).update(inventory_level=20)

    ERROR: 404 Not Found @ products/[123,456]: b'[{"status":404,"message":"The requested resource was not found."}]'

    BigCommerce allow 10 product updates at a time, so I'm trying to see if that is possible. https://developer.bigcommerce.com/api-reference/catalog/catalog-api/products/updateproducts

    opened by HaiSycamore 1
  • Updating customer password gives random 400 errors

    Updating customer password gives random 400 errors

    Overview

    I am trying to update the customer password in one of my applications. Sample code:

    import bigcommerce
    
    big_commerce_url_info = xxx
    big_commerce_store_hash = xxx
    big_commerce_client_id = xxx
    big_commerce_auth_token = xxx
    customer_id = xxx
    password = xxx
    
    try:
        api = bigcommerce.api.BigcommerceApi(client_id=big_commerce_client_id, store_hash=big_commerce_store_hash, access_token=big_commerce_auth_token)
        api.Customers.get(customer_id).update(_authentication=dict(password=password))
    except Exception as e:
        print("ERROR: ", str(e))
    

    Expected behavior

    It should update the password every single time.

    Actual behavior

    It updates the password most of the times for most customers but some times it randomly gives the following error:

    ERROR: 400 Bad Request @ customers/1705: b'[{"status":400,"message":"The field \'password\' is invalid."}]'
    

    Steps to reproduce the behavior

    Just run the code multiple times and it will randomly fail at some point.

    opened by akshatbjain 4
Releases(bigcommerce-0.22.2)
An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD.

uticker An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD. Features include: Twi

Tansu Şenyurt 1 Nov 28, 2021
Hostapd-mac-monitor - Setup a hostapd AP to conntrol the connections of specific MACs

A brief explanation This script provides way to setup a monitoring service of sp

2 Feb 03, 2022
Want to get your driver's license? Can't get a appointment because of COVID? Well I got a solution for you.

NJDMV-appoitment-alert Want to get your driver's license? Can't get a appointment because of COVID? Well I got a solution for you. We'll get you one i

Harris Spahic 3 Feb 04, 2022
Seems Like Everyone Is Posting This, Thought I Should Too, Tokens Get Locked Upon Creation And Im Not Going To Fix For Several Reasons

Member-Booster Seems Like Everyone Is Posting This, Thought I Should Too, Tokens Get Locked Upon Creation And Im Not Going To Fix For Several Reasons

Mintyz 1 Dec 28, 2021
Financial portfolio optimisation in python, including classical efficient frontier, Black-Litterman, Hierarchical Risk Parity

PyPortfolioOpt has recently been published in the Journal of Open Source Software 🎉 PyPortfolioOpt is a library that implements portfolio optimizatio

Robert Martin 3.2k Jan 02, 2023
A Telegram bot to all media and documents files to web link .

FileStreamBot A Telegram bot to all media and documents files to web link . Report a Bug | Request Feature 🍁 About This Bot : This bot will give you

Code X Mania 129 Jan 03, 2023
Discord bot developed by Delhi University Student Community!

DUSC-Bot Discord bot developed by Delhi University Student Community! Libraries Used Pycord - Documentation Features Can purge messages in bulk Drop-D

professor 1 Jan 29, 2022
A telegram bot to read RSS feeds

Telegram bot to fetch RSS feeds This is a telegram bot that fetches RSS feeds in regular intervals and send it to you. The feed sources can be added o

Santhosh Thottingal 14 Dec 15, 2022
OpenZeppelin Contracts written in Cairo for StarkNet, a decentralized ZK Rollup

OpenZeppelin Cairo Contracts A library for secure smart contract development written in Cairo for StarkNet, a decentralized ZK Rollup. ⚠️ WARNING! ⚠️

OpenZeppelin 592 Jan 04, 2023
🪣 Bitbucket Server PAT Generator

🪣 Bitbucket Server PAT Generator 🤝 Introduction Bitbucket Server (nee Stash) can hand out Personal Access Tokens (PAT) to be used in-place of user+p

reecetech 2 May 03, 2022
discord token grabber scam - eductional purposes only!

Discord-QR-Scam תופס אסימון תמונה של Discord על אודות סקריפט Python שיוצר אוטומטית קוד QR הונאה של Nitro ותופס את אסימון הדיסקורד בעת סריקה. כלי זה מד

Amit Pinchasi 0 May 22, 2022
汪汪Bot是一个Telegram Bot,用于帮助你管理一台服务器上的Docker

WangWangBot 汪汪Bot是一个Telegram Bot,用于帮助你管理一台服务器上的Docker运行的Bot。这是使用视频: 部署说明 安装运行 准备 local.env 普通版本 BOT_TOKEN=你的BOT_TOKEN ADMINS=使用,分隔的管理员ID列表 如果你使用doppl

老房东的代码练习册 56 Aug 23, 2022
RevSpotify is a fast, useful telegram bot to have Spotify music on Telegram.

RevSpotify A Telegram Bot that can download music from Spotify RevSpotify is a fast, useful telegram bot to have Spotify music on Telegram. ✨ Features

Alireza Shabani 12 Sep 12, 2022
A Sublime Text plugin that displays inline images for single-line comments formatted like `// ![](example.png)`.

Inline Images Sometimes ASCII art is not enough. Sometimes an image says more than a thousand words. This Sublime Text plugin can display images inlin

Andreas Haferburg 8 Jul 01, 2022
DaProfiler vous permet d'automatiser vos recherches sur des particuliers basés en France uniquement et d'afficher vos résultats sous forme d'arbre.

A but educatif seulement. DaProfiler DaProfiler vous permet de créer un profil sur votre target basé en France uniquement. La particularité de ce prog

Dalunacrobate 73 Dec 21, 2022
This bot plays the most recent video from the Daily Silksong News Youtube Channel whenever a specific user enters voice chat once a day.

Do you have that one friend that really likes Hollow Knight. Are they waiting for Silksong to come out? Heckle them with this Discord bot.

Tommy Rousey 2 Feb 09, 2022
Open Source Discord bot with many cool features like Weather, Balance, Avatar, User, Server, RP-commands, Gif search, YouTube search, VK post search etc.

Сокобот Дискорд бот с открытым исходным кодом. Содержит в себе экономику, полезные команды (!аватар, !юзер, !сервер и тд.), рп-команды (!обнять, !глад

serverok 2 Jan 16, 2022
A simple python discord bot with commands for moderation and utility.

Discord Bot A simple python discord bot with commands for moderation, utility and fun. Moderation $kick user reason - Kick a user from the server

3 Jan 07, 2022
The scope of this project will be to build a data ware house on Google Cloud Platform that will help answer common business questions as well as powering dashboards

The scope of this project will be to build a data ware house on Google Cloud Platform that will help answer common business questions as well as powering dashboards.

Shweta_kumawat 2 Jan 20, 2022
A simple chat api that can also work with ipb4 and chatbox+

SimpleChatApi API for chatting that can work on its own or work with Invision Community and Chatbox+. You are also welcome to create frontend for this

Anubhav K. 1 Feb 01, 2022