Magento 2 REST API integration using Python

Last updated on 14th September 2022

Magento provides REST API that allows integrators and developers to automate various tasks such as order processsing, inventory management, customer management, product management, CRM and B2B integration etc.,. There are three types of REST API endpoints in Magento depending on the type of user making the request. These are Admin endpoints, Customer endpoints and Guest endpoints. This tutorial demonstrates how to get order information from Magento 2.3(or later) using REST API calls from a Python program.

Before you can call the REST APIs from Python, you must create an integration and generate the access tokens which will be used for authentication. The endpoints related to orders are in the Admin category and you will need a admin access token to make request on these endpoints. The steps to create an integration and generate the tokens are explained in this article Enable API access on Magento

Python program to get Order details

Below is a Python script defines four functions

  • get_orders() - Gets order id and customer name for all orders

  • get_order_by_id(orderId) - Gets Order details for the specified order. Order id is passed as an argumen to this function.

  • print_order(order) - this function takes a order object as argument and prints the details to console.

The main() function first lists all the orders, then gets the details for the first order in the list and finally prints that information to the screen or standard output.

This example displays just a few fields in the Order information. Check Magento REST API documentation for a complete list of all the available fields.

import requests
import json

# Set your magento installation base url and access token
baseURL = "http://<host>/rest/default/V1/"
token = "<your_access_token>"

headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization" : 'Bearer '+ token
}

# Get all Orders
def get_orders():
    url = baseURL + "orders?searchCriteria='&fields=items[entity_id,customer_firstname,customer_lastname]"
    response = requests.request(
    "GET", 
    url,
    headers=headers
    )
    return(json.loads(response.text))  

# Get Order By ID
def get_order_by_id(orderId):
    url = baseURL + "orders/" + str(orderId)
    response = requests.request(
       "GET", 
       url,
       headers=headers
    )
    return(json.loads(response.text))  

# Print order details
def print_order(order):
    #print (order["items"])
    print ("_____________________________________________")
    print ("Order Id:", order["entity_id"])
    print ("Order Date:", order["created_at"])
    print ("Order Status:", order["status"])
    print ("Customer Name:", order["customer_firstname"], order["customer_lastname"])
    print ("Email:", order["customer_email"])
    print ("---------------------------------------------")
    print ("{:<25} {:>5} {:>10}".format("Item","Qty","Price"))
    for item in order["items"]:
        print("{:<25} {:>5} {:>10}".format(item["name"], item["qty_ordered"], item["price"])) 
    print ("---------------------------------------------")
    print ("{:<31} {:>10.2f}".format("Shipping", order["shipping_amount"]))
    print ("{:<31} {:>10.2f}".format("Total", order["total_due"]))
    print ("_____________________________________________")    

def main():
    orders = get_orders()
    for order in orders["items"]:
        print(order)
    first_order_id = (orders["items"])[0]["entity_id"]
    order = get_order_by_id(first_order_id)
    print_order(order)

if __name__ == "__main__":
    main()

Sample Output

A sample output from the above program will be like this:

{'customer_firstname': 'Kate', 'customer_lastname': 'Smith', 'entity_id': 4}
{'customer_firstname': 'Mat', 'customer_lastname': 'Thomas', 'entity_id': 5}
{'customer_firstname': 'John', 'customer_lastname': 'Doe', 'entity_id': 6}
_____________________________________________
Order Id: 4
Order Date: 2022-09-06 09:29:34
Order Status: pending
Customer Name: Kate Smith
Email: kate@smithys.co.uk
---------------------------------------------
Item                        Qty      Price
WELSH MEADOW TISSUE BOX       1       5.99
---------------------------------------------
Shipping                              5.00
Total                                10.99
_____________________________________________

Looking for Magento to CRM/ERP/Accounting system integration? Contact us for a quote.


Post a comment

Comments

Nothing yet..be the first to share wisdom.