Get a Magento 2 REST API Token With MyMagento
Let’s generate a Magento 2 REST API token using the MyMagento REST API wrapper package.
Setting the Login Credentials
Use your Magento 2 login credentials to generate an ACCESS_TOKEN
domain = 'domain.com'
username ='username'
password = 'password'
If you’re using a local installation of Magento, your domain should look like this:
domain = '127.0.0.1/path/to/magento'
Getting a Client
Now that that’s set that up, let’s start using the API.
MyMagento uses the Client
class to handle all interactions with the API
import magento
api = magento.get_api(domain=domain, username=username, password=password, local=True)
2023-02-15 01:09:05 INFO |[ MyMagento | 127_adam ]|: Authenticating adam on 127.0.0.1/magento24...
2023-02-15 01:09:06 INFO |[ MyMagento | 127_adam ]|: Logged in to adam
Setting Environment Variables
To log in faster in the future, you can set the following environment variables:
import os
os.environ['MAGENTO_DOMAIN'] = domain
os.environ['MAGENTO_USERNAME']= username
os.environ['MAGENTO_PASSWORD']= password
The Client
can now be initialized as follows
import magento
api = magento.get_api(local=True)
2023-02-15 01:09:28 INFO |[ MyMagento | 127_adam ]|: Authenticating adam on 127.0.0.1/magento24...
2023-02-15 01:09:30 INFO |[ MyMagento | 127_adam ]|: Logged in to adam