Skip to content

Instantly share code, notes, and snippets.

@nyov
Last active August 15, 2021 12:57

Revisions

  1. nyov revised this gist Nov 25, 2019. No changes.
  2. nyov revised this gist Mar 15, 2013. 2 changed files with 83 additions and 16 deletions.
    67 changes: 67 additions & 0 deletions magento-cli.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    from rauth.service import OAuth1Service

    # Create consumer key & secret in your Magento Admin interface
    # For an API Guideline see:
    # http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
    #
    # Short Magento setup explanation:
    # 1. Magento Admin > System > Web Services > REST - OAuth Consumers:
    # Add a new consumer for this script [maybe the OAuth1Service(name='') value]
    # (This creates the consumer_key and consumer_secret token for you)
    # 2. Possibly enable rewriting rules for the /api url in the Magento .htaccess
    # 3. Magento Admin > System > Web Services > REST - Roles:
    # Give the Customer account some access to stuff (using the customer authorize_url below)
    # or create an Admin account for write access (using the admin authorize_url below)
    # Give the Guest account some access for some basic functionality testing without authorization.
    # 4. Magento Admin > System > Web Services > REST - Attributes:
    # Configure ACL attributes access for the role/account configured in 3rd
    # - The customer must have a (frontend) account to login to and authorize the script.
    # - For any created Admin roles in 3rd, the role needs to be mapped to an admin user:
    # 5. Magento Admin > System > Permissions > Users:
    # Edit an admin user and under 'REST Role', tick the created Admin REST Role to map it to that account.
    # This admin will get the authorize_url to authorize your script access in the browser.

    MAGENTO_HOST = 'http://127.0.0.1'
    MAGENTO_API_BASE = '%s/api/rest/' % MAGENTO_HOST

    magento = OAuth1Service(
    name = 'magento',
    consumer_key = 'vygdq11yzaectqwbpn1h4zwlamsrpomi',
    consumer_secret = '5x5idvqc8rh4vc8lrxeg4hvple0u63dt',
    request_token_url = '%s/oauth/initiate' % MAGENTO_HOST,
    access_token_url = '%s/oauth/token' % MAGENTO_HOST,
    # Customer authorization
    #authorize_url = '%s/oauth/authorize' % MAGENTO_HOST,
    # Admin authorize url depending on admin url
    authorize_url = '%s/admin/oauth_authorize' % MAGENTO_HOST,
    base_url = MAGENTO_API_BASE
    )

    # get request token
    request_token, request_token_secret = magento.get_request_token(method='POST', params={'oauth_callback': 'oob'})

    # authorize us
    authorize_url = magento.get_authorize_url(request_token)

    print 'Visit this URL in your browser: ' + authorize_url
    code = raw_input('Paste Code from browser: ')

    session = magento.get_auth_session(request_token,
    request_token_secret,
    method='POST',
    data={'oauth_verifier': code})

    headers = {'Accept': 'application/json'}
    r = session.get('products', headers=headers)

    articles = r.json()

    for i, product in articles.items():
    id = product['sku'].encode('utf-8')
    text = product['description'].encode('utf-8')
    print '{0}. ArtNr: {1} - {2}'.format(i, id, text)

    session.close()
    32 changes: 16 additions & 16 deletions magento-rauth-example.py
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,5 @@
    #!/usr/bin/env python
    # encoding=utf-8
    # vim: set fileencoding=utf-8 :
    # -*- coding: utf-8 -*-

    from rauth.service import OAuth1Service
    import json
    @@ -28,39 +27,40 @@
    # This admin will get the authorize_url to authorize your script access in the browser.

    MAGENTO_HOST = 'http://127.0.0.1'
    MAGENTO_API_BASE = MAGENTO_HOST + '/api/rest/'
    MAGENTO_API_BASE = '%s/api/rest/' % MAGENTO_HOST

    service = OAuth1Service(
    magento = OAuth1Service(
    name = 'magento',
    consumer_key = 'vygdq11yzaectqwbpn1h4zwlamsrpomi',
    consumer_secret = '5x5idvqc8rh4vc8lrxeg4hvple0u63dt',
    request_token_url = MAGENTO_HOST + '/oauth/initiate',
    access_token_url = MAGENTO_HOST + '/oauth/token',
    request_token_url = '%s/oauth/initiate' % MAGENTO_HOST,
    access_token_url = '%s/oauth/token' % MAGENTO_HOST,
    # Customer authorization
    #authorize_url = MAGENTO_HOST + '/oauth/authorize',
    #authorize_url = '%s/oauth/authorize' % MAGENTO_HOST,
    # Admin authorize url depending on admin url
    authorize_url = MAGENTO_HOST + '/admin/oauth_authorize',
    base_url = MAGENTO_API_BASE )
    authorize_url = '%s/admin/oauth_authorize' % MAGENTO_HOST,
    base_url = MAGENTO_API_BASE
    )

    """
    # get request token
    request_token, request_token_secret = service.get_request_token(method='POST', params={'oauth_callback': 'oob'})
    request_token, request_token_secret = magento.get_request_token(method='POST', params={'oauth_callback': 'oob'})
    print 'Our request token is: ' + request_token
    print ' token secret is: ' + request_token_secret
    print
    # authorize us
    authorize_url = service.get_authorize_url(request_token)
    authorize_url = magento.get_authorize_url(request_token)
    print 'Visit this URL in your browser: ' + authorize_url
    code = raw_input('Enter PIN from browser: ')
    code = raw_input('Paste Code from browser: ')
    #session = service.get_auth_session(request_token, request_token_secret, method='POST', data=params)
    #session = service.get_auth_session(request_token, request_token_secret, method='GET', params=params)
    #session = magento.get_auth_session(request_token, request_token_secret, method='POST', data=params)
    #session = magento.get_auth_session(request_token, request_token_secret, method='GET', params=params)
    # -- get access token
    access_token, access_token_secret = service.get_access_token(request_token=request_token,
    access_token, access_token_secret = magento.get_access_token(request_token=request_token,
    request_token_secret=request_token_secret,
    method='POST',
    data={'oauth_verifier': code})
    @@ -74,7 +74,7 @@
    access_token_secret = '<save access_token here for reuse>'

    tok = access_token, access_token_secret
    session = service.get_session(token=tok, signature=None)
    session = magento.get_session(token=tok, signature=None)


    ## example GET request
  3. nyov revised this gist Mar 10, 2013. 1 changed file with 0 additions and 13 deletions.
    13 changes: 0 additions & 13 deletions rauth-session-hack.patch
    Original file line number Diff line number Diff line change
    @@ -1,13 +0,0 @@
    diff --git a/rauth/session.py b/rauth/session.py
    index af3a0e7..7aa2873 100644
    --- a/rauth/session.py
    +++ b/rauth/session.py
    @@ -139,7 +139,7 @@ class OAuth1Session(RauthSession):
    if isinstance(req_kwargs.get('params'), basestring):
    req_kwargs['params'] = dict(parse_qsl(req_kwargs['params']))

    - if isinstance(req_kwargs.get('data'), basestring):
    + if isinstance(req_kwargs.get('data'), basestring) and not isinstance(req_kwargs['headers'].get('Content-Type'), basestring):
    req_kwargs['data'] = dict(parse_qsl(req_kwargs['data']))

    entity_method = method.upper() in ENTITY_METHODS
  4. nyov revised this gist Mar 8, 2013. 1 changed file with 19 additions and 1 deletion.
    20 changes: 19 additions & 1 deletion magento-rauth-example.py
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    #!/usr/bin/env python
    # encoding=utf-8
    # vim: set fileencoding=utf-8 :

    from rauth.service import OAuth1Service
    import json
    @@ -8,12 +9,29 @@
    # Create consumer key & secret in your Magento Admin interface
    # For an API Guideline see:
    # http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
    #
    # Short Magento setup explanation:
    # 1. Magento Admin > System > Web Services > REST - OAuth Consumers:
    # Add a new consumer for this script [maybe the OAuth1Service(name='') value]
    # (This creates the consumer_key and consumer_secret token for you)
    # 2. Possibly enable rewriting rules for the /api url in the Magento .htaccess
    # 3. Magento Admin > System > Web Services > REST - Roles:
    # Give the Customer account some access to stuff (using the customer authorize_url below)
    # or create an Admin account for write access (using the admin authorize_url below)
    # Give the Guest account some access for some basic functionality testing without authorization.
    # 4. Magento Admin > System > Web Services > REST - Attributes:
    # Configure ACL attributes access for the role/account configured in 3rd
    # - The customer must have a (frontend) account to login to and authorize the script.
    # - For any created Admin roles in 3rd, the role needs to be mapped to an admin user:
    # 5. Magento Admin > System > Permissions > Users:
    # Edit an admin user and under 'REST Role', tick the created Admin REST Role to map it to that account.
    # This admin will get the authorize_url to authorize your script access in the browser.

    MAGENTO_HOST = 'http://127.0.0.1'
    MAGENTO_API_BASE = MAGENTO_HOST + '/api/rest/'

    service = OAuth1Service(
    name='magento',
    name = 'magento',
    consumer_key = 'vygdq11yzaectqwbpn1h4zwlamsrpomi',
    consumer_secret = '5x5idvqc8rh4vc8lrxeg4hvple0u63dt',
    request_token_url = MAGENTO_HOST + '/oauth/initiate',
  5. nyov revised this gist Mar 8, 2013. 1 changed file with 6 additions and 4 deletions.
    10 changes: 6 additions & 4 deletions magento-rauth-example.py
    100644 → 100755
    Original file line number Diff line number Diff line change
    @@ -104,7 +104,7 @@
    'products',
    header_auth=True,
    headers=headers,
    data=payload,
    data=json.dumps(payload),
    )

    # see if we have errors
    @@ -119,10 +119,11 @@


    # - assign new product to a category (so it will be visible in frontend)
    # FIX THIS TO A CATEGORY ID WHICH EXISTS AND IS NOT ROOT

    payload = json.dumps({'category_id': '2'})
    r = session.post(
    article_url + 'categories',
    article_url + '/categories',
    header_auth=True,
    headers=headers,
    data=payload,
    @@ -134,8 +135,9 @@
    print r.text
    quit()
    else:
    print 'Success! Product added to category.'
    article_url = urljoin(MAGENTO_API_BASE, r.headers['location'])
    print 'Success! Product added to category: %s' % (article_url)
    print r.request.headers


    session.close()
    session.close()
  6. nyov created this gist Mar 8, 2013.
    141 changes: 141 additions & 0 deletions magento-rauth-example.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,141 @@
    #!/usr/bin/env python
    # encoding=utf-8

    from rauth.service import OAuth1Service
    import json
    from urlparse import urljoin

    # Create consumer key & secret in your Magento Admin interface
    # For an API Guideline see:
    # http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html

    MAGENTO_HOST = 'http://127.0.0.1'
    MAGENTO_API_BASE = MAGENTO_HOST + '/api/rest/'

    service = OAuth1Service(
    name='magento',
    consumer_key = 'vygdq11yzaectqwbpn1h4zwlamsrpomi',
    consumer_secret = '5x5idvqc8rh4vc8lrxeg4hvple0u63dt',
    request_token_url = MAGENTO_HOST + '/oauth/initiate',
    access_token_url = MAGENTO_HOST + '/oauth/token',
    # Customer authorization
    #authorize_url = MAGENTO_HOST + '/oauth/authorize',
    # Admin authorize url depending on admin url
    authorize_url = MAGENTO_HOST + '/admin/oauth_authorize',
    base_url = MAGENTO_API_BASE )

    """
    # get request token
    request_token, request_token_secret = service.get_request_token(method='POST', params={'oauth_callback': 'oob'})
    print 'Our request token is: ' + request_token
    print ' token secret is: ' + request_token_secret
    print
    # authorize us
    authorize_url = service.get_authorize_url(request_token)
    print 'Visit this URL in your browser: ' + authorize_url
    code = raw_input('Enter PIN from browser: ')
    #session = service.get_auth_session(request_token, request_token_secret, method='POST', data=params)
    #session = service.get_auth_session(request_token, request_token_secret, method='GET', params=params)
    # -- get access token
    access_token, access_token_secret = service.get_access_token(request_token=request_token,
    request_token_secret=request_token_secret,
    method='POST',
    data={'oauth_verifier': code})
    print 'Our access token is: ' + access_token
    print ' token secret is: ' + access_token_secret
    print
    """

    access_token = '<save access_token here for reuse>'
    access_token_secret = '<save access_token here for reuse>'

    tok = access_token, access_token_secret
    session = service.get_session(token=tok, signature=None)


    ## example GET request

    headers = {'Accept': 'application/json'}
    #headers = {'Accept': 'application/xml'}

    r = session.get(
    'products',
    #'products/1/categories',
    #'customers',
    #'stockitems',
    #'products?filter[1][attribute]=entity_id&filter[1][gt]=4'
    headers=headers,
    #header_auth=True,
    )

    print r.request.headers
    print r.json()
    print


    ## example POST request

    headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}

    # - create a product

    product = """{
    "type_id": "simple",
    "attribute_set_id": "4",
    "sku": "TestArticle1",
    "name": "Test Article 70mm² M12",
    "price": "3.5200",
    "description": "This Product has the bare minimum required attributes to get inserted",
    "short_description": "Test Article 70mm² M12",
    "weight": "0.0000",
    "status": "1",
    "visibility": "4",
    "tax_class_id": "2"
    }"""

    payload = json.loads(product)
    r = session.post(
    'products',
    header_auth=True,
    headers=headers,
    data=payload,
    )

    # see if we have errors
    if r.status_code != 200:
    print 'Error!'
    print r.text
    quit()
    else:
    # catch the returned Location redirect to the new product
    article_url = urljoin(MAGENTO_API_BASE, r.headers['location'])
    print 'New product inserted as: %s' % (article_url)


    # - assign new product to a category (so it will be visible in frontend)

    payload = json.dumps({'category_id': '2'})
    r = session.post(
    article_url + 'categories',
    header_auth=True,
    headers=headers,
    data=payload,
    )

    # see if we have errors
    if r.status_code != 200:
    print 'Error!'
    print r.text
    quit()
    else:
    print 'Success! Product added to category.'
    print r.request.headers


    session.close()
    13 changes: 13 additions & 0 deletions rauth-session-hack.patch
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    diff --git a/rauth/session.py b/rauth/session.py
    index af3a0e7..7aa2873 100644
    --- a/rauth/session.py
    +++ b/rauth/session.py
    @@ -139,7 +139,7 @@ class OAuth1Session(RauthSession):
    if isinstance(req_kwargs.get('params'), basestring):
    req_kwargs['params'] = dict(parse_qsl(req_kwargs['params']))

    - if isinstance(req_kwargs.get('data'), basestring):
    + if isinstance(req_kwargs.get('data'), basestring) and not isinstance(req_kwargs['headers'].get('Content-Type'), basestring):
    req_kwargs['data'] = dict(parse_qsl(req_kwargs['data']))

    entity_method = method.upper() in ENTITY_METHODS