1

I'm new to Magento API and actually a python programmer, there are some APIs I should connect to them through Rest and I stick to the first step of authentication with OAuth for getting access tokens and this stuff. Can anyone, please, help me through this in a very clear way. I've got my consumer key and secret and want to connect and use the APIs.

asked Nov 14, 2017 at 17:21

1 Answer 1

0

In the magento2 admin panel please create your secrets by following the path: Stores > Settings > Configuration > Services > OAuth > Access Token Expiration > Admin Token Lifetime (hours).

The following code block shows an autorizator class that can be used:

from requests_oauthlib import OAuth1
class Authorizator:
 """
 Authorization Class
 """
 def __init__(self, consumer_key, consumer_key_secret, access_token, access_token_secret):
 self.consumer_key = consumer_key
 self.consumer_key_secret = consumer_key_secret
 self.access_token = access_token
 self.access_token_secret = access_token_secret
 def get_authorization_object(self) -> OAuth1:
 """
 A function that returns the authorization
 :return: An authorization object.
 :rtype: OAuth1
 """
 magento_auth = OAuth1(self.consumer_key,
 client_secret=self.consumer_key_secret,
 resource_owner_key=self.access_token,
 resource_owner_secret=self.access_token_secret)
 return magento_auth

To retrieve the magento2_authenticator object just use the following stmt in your code:

consumer_key = ""
consumer_key_secret = ""
access_token = ""
access_token_secret = ""
authorizator = Authorizator(consumer_key, consumer_key_secret, access_token, access_token_secret)
magento2_auth = authorizator.get_authorization_object()

Ideally you can pass the secrets by argparse instead of hardcoding them here.

Use the object then in your request - The following code block describes how to retrieve the current categories.

base_url = "https://yourstoredomain.com"
endpoint = r"/rest/all/V1/categories"
params = {"searchCriteria[currentPage]": "0"}
response = requests.get(url=base_url + endpoint,
 auth=magento2_auth,
 params=params
 )
response.raise_for_status()

If the application is getting bigger please use the magento2 authorizator object as dependency injection for the relevant functions.

answered Mar 12, 2024 at 12:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.