Skip to content

Instantly share code, notes, and snippets.

@ju5t
Last active March 12, 2018 13:38
Show Gist options
  • Save ju5t/b2822b0a6ce132adb4b5e0f896d46e6b to your computer and use it in GitHub Desktop.
Save ju5t/b2822b0a6ce132adb4b5e0f896d46e6b to your computer and use it in GitHub Desktop.
#14054 Magento2 API
import os
import requests
# Magento
magento_endpoint = os.environ['MAGENTO_ENDPOINT']
magento_username = os.environ['MAGENTO_USERNAME']
magento_password = os.environ['MAGENTO_PASSWORD']
class Magento2:
endpoint = None
headers = None
def __init__(self, endpoint=None, username=None, password=None):
self.endpoint = endpoint
# Connect to the API
credentials = {'username': username, 'password': password}
authentication = requests.post('{}'
'/rest/V1/integration/admin/token'.
format(endpoint),
json=credentials)
# The request failed
if authentication.status_code != 200:
print('Authentication error')
# Set authentication headers that we will reuse in API calls
self.headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(authentication.json())
}
magento = Magento2(endpoint=magento_endpoint, username=magento_username,
password=magento_password)
customer = {
'customer':
{
'store_id': 1,
'website_id': 1,
'group_id': 1,
'firstname': 'Anonymous',
'lastname': 'Anonymous',
'email': 'valid@email.org',
'taxvat': None,
'addresses': [
{
'firstname': 'Anonymous',
'lastname': 'Anonymous',
'telephone': '0123456789',
'company': 'Anonymous Inc.',
'street': ['Where the streets have no name 1'],
'postcode': '1000AA',
'city': 'Amsterdam',
'country_id': 'NL',
'default_billing': False,
'default_shipping': False
},
{
'firstname': 'Anonymous',
'lastname': 'Anonymous',
'telephone': '0123456789',
'company': 'Anonymous BV',
'street': ['Where the streets have no name 1'],
'postcode': '1000AA',
'city': 'Amsterdam',
'country_id': 'NL',
'default_billing': False,
'default_shipping': False
}
]
}
}
# Save the customer
save = requests.post('{}/rest/V1/customers/'.format(
magento.endpoint), headers=magento.headers,
json=customer)
print(save.json())
save = requests.put('{}/rest/V1/customers/{}'.format(
magento.endpoint, 1), headers=magento.headers,
json=customer)
print(save.json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment