### Install and Set Up Pre-commit Hooks
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Run these commands to install pre-commit and set up the git hook scripts for local development.
```shell
pip install -r requirements.txt
pre-commit install
```
--------------------------------
### Build and Install Development Version
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Commands to build a source distribution of the library and install it using pip. This is for development purposes.
```shell
python setup.py sdist
pip install --upgrade dist/ShopifyAPI-*.tar.gz
```
--------------------------------
### Session Setup
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Set up the Shopify API key and secret for authentication.
```APIDOC
## Session Setup
### Description
Configure the Shopify API key and secret to enable authentication for your application.
### Method
```python
shopify.Session.setup(api_key=API_KEY, secret=API_SECRET)
```
### Parameters
- **api_key** (string) - Required - Your Shopify API Key.
- **secret** (string) - Required - Your Shopify API Secret Key.
```
--------------------------------
### Install or Upgrade ShopifyAPI
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Use pip to install or upgrade to the latest release of the ShopifyAPI library.
```shell
pip install --upgrade ShopifyAPI
```
--------------------------------
### Create Permission URL
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Initiate the OAuth process to get authorization from a shop.
```APIDOC
## Create Permission URL
### Description
Generate a URL to redirect users to Shopify for app authorization. This is the first step in the OAuth flow for public apps.
### Method
```python
shop_url = "SHOP_NAME.myshopify.com"
api_version = '2024-07'
state = binascii.b2a_hex(os.urandom(15)).decode("utf-8")
redirect_uri = "http://myapp.com/auth/shopify/callback"
scopes = ['read_products', 'read_orders']
newSession = shopify.Session(shop_url, api_version)
auth_url = newSession.create_permission_url(redirect_uri, scopes, state)
# redirect to auth_url
```
### Parameters
- **shop_url** (string) - Required - The shop's myshopify.com URL.
- **api_version** (string) - Required - The Shopify API version to use.
- **redirect_uri** (string) - Required - The URL to redirect to after authorization.
- **scopes** (list of strings) - Required - A list of permissions the app is requesting.
- **state** (string) - Required - A unique token to prevent CSRF attacks.
```
--------------------------------
### Product Resource Operations
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Examples of creating, finding, updating, and deleting Product resources using the pyactiveresource library.
```APIDOC
## Product Resource Operations
### Description
Demonstrates basic CRUD operations for Product resources.
### Method
- `shopify.Product()`: Instantiate a new Product object.
- `product.save()`: Create or update the product on Shopify.
- `shopify.Product.exists(id)`: Check if a product with the given ID exists.
- `shopify.Product.find(id)`: Retrieve a specific product by its ID.
- `product.destroy()`: Delete the product from Shopify.
### Example Usage
```python
# Note: REST API examples will be deprecated in 2025
product = shopify.Product()
product.title = "Shopify Logo T-Shirt"
product.id # => 292082188312
product.save() # => True
shopify.Product.exists(product.id) # => True
product = shopify.Product.find(292082188312)
# Resource holding our newly created Product object
# Inspect attributes with product.attributes
product.price = 19.99
product.save() # => True
product.destroy()
# Delete the resource from the remote server (i.e. Shopify)
```
```
--------------------------------
### Finding Orders with Parameters
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Example of retrieving a list of orders with specific filters and limits.
```APIDOC
## Finding Orders with Parameters
### Description
Retrieves a list of orders based on specified criteria like status and limit.
### Method
- `shopify.Order.find(status, limit)`: Find orders matching the given parameters.
### Parameters
#### Query Parameters
- **status** (string) - Required - The status of the orders to retrieve (e.g., "open").
- **limit** (string) - Optional - The maximum number of orders to return.
### Example Usage
```python
new_orders = shopify.Order.find(status="open", limit="50")
```
```
--------------------------------
### Setup Global API Credentials
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Configure your application's global API key and secret once at startup. These are required for generating OAuth URLs and validating request signatures.
```python
import shopify
# Set global credentials from your Shopify Partners Dashboard app
shopify.Session.setup(api_key="your_api_key", secret="your_api_secret")
```
--------------------------------
### Session Setup
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Configure the global API key and secret once at application startup. These credentials are used to generate OAuth URLs and validate HMAC signatures on all incoming Shopify requests.
```APIDOC
## Session.setup()
### Description
Configure the global API key and secret once at application startup. These credentials are used to generate OAuth URLs and validate HMAC signatures on all incoming Shopify requests.
### Method
`shopify.Session.setup(api_key: str, secret: str)`
### Parameters
- **api_key** (string) - Required - Your Shopify API key.
- **secret** (string) - Required - Your Shopify API secret.
### Request Example
```python
import shopify
shopify.Session.setup(api_key="your_api_key", secret="your_api_secret")
```
```
--------------------------------
### GraphQL API Execution
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Example of executing a basic GraphQL query against the Shopify API.
```APIDOC
## GraphQL API Execution
### Description
Executes a GraphQL query against the Shopify API to retrieve shop information.
### Method
- `shopify.GraphQL().execute(query)`: Executes the provided GraphQL query.
### Parameters
#### Request Body
- **query** (string) - Required - The GraphQL query string.
### Request Example
```python
result = shopify.GraphQL().execute('{ shop { name id } }')
```
```
--------------------------------
### Create, Find, Update, and Delete Products (REST API)
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Demonstrates basic CRUD operations for products using the REST API. Note that REST API examples will be deprecated in 2025. Ensure pyactiveresource is understood as the underlying library.
```python
product = shopify.Product()
product.title = "Shopify Logo T-Shirt"
product.id # => 292082188312
product.save() # => True
shopify.Product.exists(product.id) # => True
product = shopify.Product.find(292082188312)
# Resource holding our newly created Product object
# Inspect attributes with product.attributes
product.price = 19.99
product.save() # => True
product.destroy()
# Delete the resource from the remote server (i.e. Shopify)
```
--------------------------------
### Setup Shopify API Keys
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Configure the Shopify API with your unique API key and secret key for authentication. Ensure these are securely stored and accessed.
```python
import shopify
shopify.Session.setup(api_key=API_KEY, secret=API_SECRET)
```
--------------------------------
### Activate Session and Make API Requests
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Activate the authenticated session to make authorized API calls. This example demonstrates fetching shop information and a specific product using the REST API, and executing a GraphQL query. Remember to clear the session when done.
```python
session = shopify.Session(shop_url, api_version, access_token)
shopify.ShopifyResource.activate_session(session)
# Note: REST API examples will be deprecated in 2025
shop = shopify.Shop.current() # Get the current shop
product = shopify.Product.find(179761209) # Get a specific product
# GraphQL API example
shopify.GraphQL().execute("{ shop { name id } }")
```
--------------------------------
### Accessing Prefixed Resources (REST API)
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Example of how to find a fulfillment resource, which is prefixed by its parent order. This uses the REST API and will be deprecated.
```python
# Note: This REST API example will be deprecated in the future
shopify.Fulfillment.find(255858046, order_id=450789469)
```
--------------------------------
### GraphQL API with Variables and Operation Name
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Example of executing a specific GraphQL operation with variables and a named query from a document.
```APIDOC
## GraphQL API with Variables and Operation Name
### Description
Executes a specific named GraphQL operation from a document, providing variables for the query.
### Method
- `shopify.GraphQL().execute(query, variables, operation_name)`: Executes a GraphQL query with specified variables and operation name.
### Parameters
#### Request Body
- **query** (string) - Required - The GraphQL query document containing multiple operations.
- **variables** (object) - Optional - A dictionary of variables to pass to the GraphQL query.
- **operation_name** (string) - Optional - The name of the specific operation to execute within the document.
### Request Example
```python
# Load the document with both queries
document = Path("./order_queries.graphql").read_text()
# Specify the named operation to execute, and the parameters for the query
result = shopify.GraphQL().execute(
query=document,
variables={"order_id": "gid://shopify/Order/12345"},
operation_name="GetOneOrder",
)
```
```
--------------------------------
### Run Tests for the Development Version
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Commands to upgrade setuptools and run tests for the library directly from the source tree.
```shell
pip install setuptools --upgrade
python setup.py test
```
--------------------------------
### Create Application Charge
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Initiate the creation of an application charge for a public app. Set the charge name, price, and a return URL for post-approval redirection. Use `test: True` for testing on development stores.
```python
application_charge = shopify.ApplicationCharge.create({
'name': 'My public app',
'price': 123,
'test': True,
'return_url': 'https://domain.com/approve'
})
# Redirect user to application_charge.confirmation_url so they can approve the charge
```
--------------------------------
### Cursor Pagination
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Demonstrates how to use cursor-based pagination to navigate through resources.
```APIDOC
## Cursor Pagination
### Description
Provides methods for navigating through paginated results using cursors.
### Method
- `shopify.Product.find()`: Retrieves the first page of products.
- `page.has_next_page()`: Checks if there is a next page of results.
- `page.next_page()`: Retrieves the next page of results.
- `page.next_page_url`: Returns the URL for the next page.
- `shopify.Product.find(from_=url)`: Retrieves results from a specific URL.
### Example Usage
```python
page1 = shopify.Product.find()
if page1.has_next_page():
page2 = page1.next_page()
# to persist across requests you can use next_page_url and previous_page_url
next_url = page1.next_page_url
page2 = shopify.Product.find(from_=next_url)
```
```
--------------------------------
### Manage Products with `shopify.Product`
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Perform CRUD operations on products, including listing with filters, finding single products, creating, updating, counting, checking existence, deleting, and retrieving associated collections.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# List products with filters
products = shopify.Product.find(limit=10, status="active")
for p in products:
print(p.title, p.price_range()) # price_range() => "9.99 - 29.99"
# Find a single product
product = shopify.Product.find(632910392)
print(product.title) # => "IPod Nano - 8GB"
print(product.attributes) # dict of all fields
# Create a product
new_product = shopify.Product()
new_product.title = "Shopify Logo T-Shirt"
new_product.body_html = "Great product!"
new_product.vendor = "My Store"
new_product.product_type = "T-Shirt"
new_product.tags = "cotton, summer"
saved = new_product.save() # => True
print(new_product.id) # => assigned ID
# Update a product
product = shopify.Product.find(632910392)
product.title = "Updated Title"
product.save() # => True
# Count and check existence
count = shopify.Product.count()
print(count) # => 42
print(shopify.Product.exists(632910392)) # => True
# Delete a product
product.destroy()
# Get collections for a product
collections = product.collections()
```
--------------------------------
### Cursor-Based Pagination
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Implements cursor-based pagination for retrieving resources like products. Shows how to fetch subsequent pages using `next_page()` and `next_page_url`.
```python
import shopify
page1 = shopify.Product.find()
if page1.has_next_page():
page2 = page1.next_page()
# to persist across requests you can use next_page_url and previous_page_url
next_url = page1.next_page_url
page2 = shopify.Product.find(from_=next_url)
```
--------------------------------
### Manage Orders with `shopify.Order`
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Manage Shopify orders, including finding orders by status or customer, retrieving a single order, closing, re-opening, canceling, capturing payments, and listing order transactions.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Find open orders
open_orders = shopify.Order.find(status="open", limit=50)
for order in open_orders:
print(order.id, order.email, order.total_price)
# Find orders for a specific customer
customer_orders = shopify.Order.find(customer_id=207119551)
# Get a single order
order = shopify.Order.find(450789469)
print(order.financial_status) # => "partially_paid"
# Close an order
order.close()
print(order.status) # => "closed"
# Re-open an order
order.open()
# Cancel an order
order.cancel(reason="customer", email=True)
# Capture payment
transaction = order.capture(amount="10.00")
print(transaction.status) # => "success"
# Get transactions for an order
transactions = order.transactions()
for t in transactions:
print(t.kind, t.amount) # => "authorization" "150.00"
```
--------------------------------
### Execute a Simple GraphQL Query
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Executes a basic GraphQL query to retrieve the shop's name and ID. Requires an activated session and a GraphQL client.
```python
result = shopify.GraphQL().execute('{ shop { name id } }')
```
--------------------------------
### Customer Resource
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Manage customers by searching, finding by ID, creating new customers, retrieving their orders, sending account invites, and adding metafields.
```APIDOC
## Customer Resource — `shopify.Customer`
Find, create, and manage customers with search, invitation, and order-scoped lookup.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Search customers
results = shopify.Customer.search(query="Bob Norman", limit=10)
for customer in results:
print(customer.first_name, customer.last_name, customer.email)
# Find by ID
customer = shopify.Customer.find(207119551)
print(customer.email) # => "bob.norman@example.com"
print(customer.orders_count) # => 1
# Create a customer
new_customer = shopify.Customer()
new_customer.first_name = "Jane"
new_customer.last_name = "Doe"
new_customer.email = "jane.doe@example.com"
new_customer.phone = "+16135551111"
new_customer.verified_email = True
new_customer.save()
# Get a customer's orders
orders = customer.orders()
# Send account invite
invite = shopify.CustomerInvite()
invite.subject = "Welcome to our store!"
invite.custom_message = "We're excited to have you!"
customer.send_invite(invite)
# Add a metafield
from shopify import Metafield
mf = shopify.Metafield()
mf.namespace = "my_app"
mf.key = "loyalty_points"
mf.value = 100
mf.type = "number_integer"
customer.add_metafield(mf)
```
```
--------------------------------
### Construct ApiAccess Objects
Source: https://github.com/shopify/shopify_python_api/blob/main/docs/api-access.md
Instantiate ApiAccess objects using either a list of scope strings or a single comma-delimited string.
```python
api_access = ApiAccess(["read_products", "write_orders"])
```
```python
another_api_access = ApiAccess("read_products, write_products, unauthenticated_read_themes")
```
--------------------------------
### Manage Shopify Webhooks
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Create, list, and delete webhooks for real-time event notifications using shopify.Webhook.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Create a webhook
webhook = shopify.Webhook()
webhook.topic = "orders/create"
webhook.address = "https://myapp.com/webhooks/orders"
webhook.format = "json"
webhook.save()
print(webhook.id) # => assigned ID
# List all webhooks
webhooks = shopify.Webhook.find()
for wh in webhooks:
print(wh.topic, wh.address)
# Delete a webhook
webhook = shopify.Webhook.find(4759306)
webhook.destroy()
```
--------------------------------
### Create Shopify Application Charges
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Use this snippet to create one-time or recurring application charges. Ensure to remove `test: True` for production environments. The `confirmation_url` should be used to redirect the user for approval.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# One-time charge
charge = shopify.ApplicationCharge.create({
"name": "Premium Feature Unlock",
"price": 9.99,
"test": True, # Remove for production
"return_url": "https://myapp.com/billing/callback",
})
print(charge.confirmation_url) # Redirect user here to approve
# After merchant approves, check status
activated_charge = shopify.ApplicationCharge.find(charge.id)
print(activated_charge.status) # => "active"
# Recurring subscription
recurring_charge = shopify.RecurringApplicationCharge.create({
"name": "Monthly Plan",
"price": 29.99,
"trial_days": 14,
"test": True,
"return_url": "https://myapp.com/billing/subscription/callback",
})
print(recurring_charge.confirmation_url)
# Usage charge against an active recurring charge
usage = shopify.UsageCharge.create({
"description": "Extra API calls",
"price": 1.00,
"recurring_application_charge_id": recurring_charge.id,
})
```
--------------------------------
### Find Product
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Retrieve a specific product by its ID.
```APIDOC
## Find Product
### Description
Get details for a specific product using its unique identifier.
### Method
```python
product = shopify.Product.find(179761209)
```
### Parameters
- **id** (integer) - Required - The ID of the product to retrieve.
```
--------------------------------
### Private App Authentication with Full Session
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Authenticate a private app using its password as the access token within a full session. Remember to activate and clear the session appropriately.
```python
session = shopify.Session(shop_url, api_version, private_app_password)
shopify.ShopifyResource.activate_session(session)
# ...
shopify.ShopifyResource.clear_session()
```
--------------------------------
### Manage Shopify Customers
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Search, find, create, and manage customers using the shopify.Customer resource. Includes adding metafields and sending invites.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Search customers
results = shopify.Customer.search(query="Bob Norman", limit=10)
for customer in results:
print(customer.first_name, customer.last_name, customer.email)
# Find by ID
customer = shopify.Customer.find(207119551)
print(customer.email) # => "bob.norman@example.com"
print(customer.orders_count) # => 1
# Create a customer
new_customer = shopify.Customer()
new_customer.first_name = "Jane"
new_customer.last_name = "Doe"
new_customer.email = "jane.doe@example.com"
new_customer.phone = "+16135551111"
new_customer.verified_email = True
new_customer.save()
# Get a customer's orders
orders = customer.orders()
# Send account invite
invite = shopify.CustomerInvite()
invite.subject = "Welcome to our store!"
invite.custom_message = "We're excited to have you!"
customer.send_invite(invite)
# Add a metafield
from shopify import Metafield
mf = shopify.Metafield()
mf.namespace = "my_app"
mf.key = "loyalty_points"
mf.value = 100
mf.type = "number_integer"
customer.add_metafield(mf)
```
--------------------------------
### Manage Shopify API Versioning with ApiVersion
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Use `ApiVersion`, `Release`, or `Unstable` to manage API versions. Known versions are pre-defined, and any valid date-format version string is accepted. `Unstable` is for preview features.
```python
import shopify
from shopify.api_version import ApiVersion, Release, Unstable
# All known versions are pre-defined at import time
# Available: 2021-10, 2022-01, 2022-04, ..., 2024-07, 2024-10, unstable
# Use a known release version
session = shopify.Session("example-shop.myshopify.com", "2024-10", "shpat_abc123")
print(session.api_version.name) # => "2024-10"
print(session.api_version.stable) # => True
print(session.site)
# => "https://example-shop.myshopify.com/admin/api/2024-10"
# Dynamically create a valid but unknown release version
release = ApiVersion.coerce_to_version("2025-01")
print(release.stable) # => True
# Use unstable for preview APIs
unstable_session = shopify.Session("example-shop.myshopify.com", "unstable", "shpat_abc123")
print(unstable_session.api_version.stable) # => False
```
--------------------------------
### Execute Named GraphQL Operations with Variables
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Demonstrates executing a specific named GraphQL operation ('GetOneOrder') with provided variables. The GraphQL document contains multiple operations and a fragment.
```graphql
# ./order_queries.graphql
framgent OrderInfo on Order {
id
name
createdAt
}
query GetOneOrder($order_id: ID!){
node(id: $order_id){
...OrderInfo
}
}
query GetManyOrders($order_ids: [ID]!){
nodes(ids: $order_ids){
...OrderInfo
}
}
```
```python
# Load the document with both queries
document = Path("./order_queries.graphql").read_text()
# Specify the named operation to execute, and the parameters for the query
result = shopify.GraphQL().execute(
query=document,
variables={"order_id": "gid://shopify/Order/12345"},
operation_name="GetOneOrder",
)
```
--------------------------------
### Execute GraphQL Queries and Mutations
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Use `shopify.GraphQL().execute()` to interact with the Shopify Admin GraphQL API. Supports variables and named operations for complex requests. Recommended over REST API for new development.
```python
import json
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Simple query
result = shopify.GraphQL().execute("{ shop { name id currencyCode } }")
data = json.loads(result)
print(data["data"]["shop"]["name"]) # => "Example Shop"
# Query with variables and named operations
document = """
fragment OrderInfo on Order {
id
name
createdAt
totalPriceSet { shopMoney { amount currencyCode } }
}
query GetOneOrder($order_id: ID!) {
node(id: $order_id) { ...OrderInfo }
}
query GetManyOrders($order_ids: [ID]!) {
nodes(ids: $order_ids) { ...OrderInfo }
}
"""
result = shopify.GraphQL().execute(
query=document,
variables={"order_id": "gid://shopify/Order/12345"},
operation_name="GetOneOrder",
)
data = json.loads(result)
print(data["data"]["node"]["name"]) # => "#1001"
# Mutation: create a product tag
mutation = """
mutation tagsAdd($id: ID!, $tags: [String!]!) {
tagsAdd(id: $id, tags: $tags) {
node { id }
userErrors { field message }
}
}
"""
result = shopify.GraphQL().execute(
query=mutation,
variables={"id": "gid://shopify/Product/123", "tags": ["sale", "featured"]},
operation_name="tagsAdd",
)
```
--------------------------------
### Webhook Resource
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Create and manage Shopify webhooks to receive real-time event notifications.
```APIDOC
## Webhook Resource — `shopify.Webhook`
Create and manage Shopify webhooks to receive real-time event notifications.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Create a webhook
webhook = shopify.Webhook()
webhook.topic = "orders/create"
webhook.address = "https://myapp.com/webhooks/orders"
webhook.format = "json"
webhook.save()
print(webhook.id) # => assigned ID
# List all webhooks
webhooks = shopify.Webhook.find()
for wh in webhooks:
print(wh.topic, wh.address)
# Delete a webhook
webhook = shopify.Webhook.find(4759306)
webhook.destroy()
```
```
--------------------------------
### Create Application Charge
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Create a new application charge for a public app.
```APIDOC
## Create Application Charge
### Description
Initiate the creation of an application charge. This is used for billing public applications.
### Method
```python
application_charge = shopify.ApplicationCharge.create({
'name': 'My public app',
'price': 123,
'test': True,
'return_url': 'https://domain.com/approve'
})
# Redirect user to application_charge.confirmation_url so they can approve the charge
```
### Parameters
- **charge_data** (object) - Required - An object containing charge details:
- **name** (string) - Required - The name of the charge.
- **price** (number) - Required - The price of the charge.
- **test** (boolean) - Optional - Set to `True` for testing.
- **return_url** (string) - Required - The URL to redirect to after charge approval.
```
--------------------------------
### Activating a Session
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Sets the active shop credentials on all resource classes for the current thread. Every subsequent REST or GraphQL call uses this session. Always clear the session when done to avoid credential leakage across requests.
```APIDOC
## Activating a Session
### Description
Sets the active shop credentials on all resource classes for the current thread. Every subsequent REST or GraphQL call uses this session. Always clear the session when done to avoid credential leakage across requests.
### Method
`shopify.ShopifyResource.activate_session(session: shopify.Session)`
`shopify.ShopifyResource.clear_session()`
### Parameters
- **activate_session**: `session` (shopify.Session) - The session object to activate.
### Request Example
```python
import shopify
shopify.Session.setup(api_key="your_api_key", secret="your_api_secret")
session = shopify.Session("example-shop.myshopify.com", "2024-10", "shpat_abc123")
shopify.ShopifyResource.activate_session(session)
try:
shop = shopify.Shop.current()
print(shop.name)
print(shop.email)
print(shop.currency)
finally:
shopify.ShopifyResource.clear_session()
```
```
--------------------------------
### Use Temporary Session
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Utilize a temporary session for executing commands, which automatically handles session cleanup. This is useful for short-lived operations.
```python
with shopify.Session.temp(shop_url, api_version, token):
product = shopify.Product.find()
```
--------------------------------
### Private App Session (Full)
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Authenticate using a private app password with a full session.
```APIDOC
## Private App Session (Full)
### Description
Set up and activate a session for a private app using its password as the access token.
### Method
```python
session = shopify.Session(shop_url, api_version, private_app_password)
shopify.ShopifyResource.activate_session(session)
# ... API calls ...
shopify.ShopifyResource.clear_session()
```
### Parameters
- **shop_url** (string) - Required - The shop's myshopify.com URL.
- **api_version** (string) - Required - The Shopify API version to use.
- **private_app_password** (string) - Required - The password for the private app.
```
--------------------------------
### Current Shop
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Retrieve information about the currently authenticated shop.
```APIDOC
## Current Shop
### Description
Fetch details for the shop associated with the currently active session.
### Method
```python
shop = shopify.Shop.current()
```
### Response
#### Success Response (200)
- **shop** (object) - Contains shop details.
```
--------------------------------
### Initiate OAuth Authentication URL
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Generate the authorization URL required to initiate the OAuth flow. This URL directs users to grant your app permission to access their shop data. Ensure the redirect URI and scopes are correctly configured.
```python
import shopify
import binascii
import os
shop_url = "SHOP_NAME.myshopify.com"
api_version = '2024-07'
state = binascii.b2a_hex(os.urandom(15)).decode("utf-8")
redirect_uri = "http://myapp.com/auth/shopify/callback"
# `scope` should be omitted if provided by app's TOML
scopes = ['read_products', 'read_orders']
newSession = shopify.Session(shop_url, api_version)
# `scope` should be omitted if provided by app's TOML
auth_url = newSession.create_permission_url(redirect_uri, scopes, state)
# redirect to auth_url
```
--------------------------------
### Billing - ApplicationCharge / RecurringApplicationCharge
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Create one-time and recurring app charges for Shopify's billing system. Use `test: True` on development stores.
```APIDOC
## Billing — `ApplicationCharge` / `RecurringApplicationCharge`
Create one-time and recurring app charges for Shopify's billing system. Use `test: True` on development stores.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# One-time charge
charge = shopify.ApplicationCharge.create({
"name": "Premium Feature Unlock",
"price": 9.99,
"test": True, # Remove for production
"return_url": "https://myapp.com/billing/callback",
})
print(charge.confirmation_url) # Redirect user here to approve
# After merchant approves, check status
activated_charge = shopify.ApplicationCharge.find(charge.id)
print(activated_charge.status) # => "active"
# Recurring subscription
recurring_charge = shopify.RecurringApplicationCharge.create({
"name": "Monthly Plan",
"price": 29.99,
"trial_days": 14,
"test": True,
"return_url": "https://myapp.com/billing/subscription/callback",
})
print(recurring_charge.confirmation_url)
# Usage charge against an active recurring charge
usage = shopify.UsageCharge.create({
"description": "Extra API calls",
"price": 1.00,
"recurring_application_charge_id": recurring_charge.id,
})
```
```
--------------------------------
### Activate Application Charge
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Activate a previously created application charge.
```APIDOC
## Activate Application Charge
### Description
Activate an application charge after the user has approved it. Note: This step might not be necessary for API versions 2021-01 and later.
### Method
```python
charge = shopify.ApplicationCharge.find(charge_id)
shopify.ApplicationCharge.activate(charge)
```
### Parameters
- **charge** (object) - Required - The charge object to activate, typically obtained via `shopify.ApplicationCharge.find(charge_id)`.
```
--------------------------------
### Manage Shopify Fulfillments
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Find, cancel, complete, and update tracking information for order fulfillments using shopify.Fulfillment.
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Find fulfillments for an order (prefix required)
fulfillments = shopify.Fulfillment.find(order_id=450789469)
for f in fulfillments:
print(f.id, f.status, f.tracking_number)
# Find a specific fulfillment
fulfillment = shopify.Fulfillment.find(255858046, order_id=450789469)
# Cancel a fulfillment
fulfillment.cancel()
# Complete a fulfillment
fulfillment.complete()
# Update tracking information
tracking_info = {
"number": "1Z001985ZX91234567",
"url": "https://www.ups.com/track?num=1Z001985ZX91234567",
"company": "UPS",
}
fulfillment.update_tracking(tracking_info=tracking_info, notify_customer=True)
```
--------------------------------
### Execute GraphQL Query
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Execute a custom GraphQL query against the Shopify API.
```APIDOC
## Execute GraphQL Query
### Description
Run a GraphQL query to fetch specific data from Shopify.
### Method
```python
shopify.GraphQL().execute("{ shop { name id } }")
```
### Parameters
- **query** (string) - Required - The GraphQL query string.
```
--------------------------------
### Private App Authentication with Temporary Session
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Use a temporary session for private app authentication with a private app password. This simplifies session management for brief operations.
```python
with shopify.Session.temp(shop_url, api_version, private_app_password):
shopify.GraphQL().execute("{ shop { name id } }")
```
--------------------------------
### Product Resource
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Provides CRUD operations for Shopify products, including helper methods for collection membership, variant management, and metafields.
```APIDOC
## shopify.Product
### Description
Provides CRUD operations for Shopify products, including helper methods for collection membership, variant management, and metafields.
### Methods
- **`shopify.Product.find(*args, **kwargs)`**: Lists products with optional filters or finds a single product by ID.
- **`shopify.Product.count(*args, **kwargs)`**: Counts the number of products.
- **`shopify.Product.exists(id)`**: Checks if a product with the given ID exists.
- **`product.save()`**: Creates or updates a product.
- **`product.destroy()`**: Deletes a product.
- **`product.collections()`**: Retrieves the collections a product belongs to.
### Parameters
- **`find`**: Accepts `limit`, `status`, and product IDs.
- **`save`**: No explicit parameters, operates on the product instance.
- **`destroy`**: No explicit parameters, operates on the product instance.
### Request Example
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# List products with filters
products = shopify.Product.find(limit=10, status="active")
for p in products:
print(p.title, p.price_range())
# Find a single product
product = shopify.Product.find(632910392)
print(product.title)
print(product.attributes)
# Create a product
new_product = shopify.Product()
new_product.title = "Shopify Logo T-Shirt"
new_product.body_html = "Great product!"
new_product.vendor = "My Store"
new_product.product_type = "T-Shirt"
new_product.tags = "cotton, summer"
saved = new_product.save()
print(new_product.id)
# Update a product
product = shopify.Product.find(632910392)
product.title = "Updated Title"
product.save()
# Count and check existence
count = shopify.Product.count()
print(count)
print(shopify.Product.exists(632910392))
# Delete a product
product.destroy()
# Get collections for a product
collections = product.collections()
```
```
--------------------------------
### Order Resource
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Manage Shopify orders with support for open/close/cancel actions, transaction capture, and customer-scoped lookup.
```APIDOC
## shopify.Order
### Description
Manage Shopify orders with support for open/close/cancel actions, transaction capture, and customer-scoped lookup.
### Methods
- **`shopify.Order.find(*args, **kwargs)`**: Finds orders with optional filters like `status` or `customer_id`.
- **`shopify.Order.find(id)`**: Retrieves a single order by its ID.
- **`order.close()`**: Closes an order.
- **`order.open()`**: Re-opens a closed order.
- **`order.cancel(reason=None, email=False)`**: Cancels an order.
- **`order.capture(amount=None)`**: Captures payment for an order.
- **`order.transactions()`**: Retrieves all transactions associated with an order.
### Parameters
- **`find`**: Accepts `status`, `limit`, `customer_id`, and order IDs.
- **`cancel`**: `reason` (string), `email` (boolean).
- **`capture`**: `amount` (string).
### Request Example
```python
import shopify
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Find open orders
open_orders = shopify.Order.find(status="open", limit=50)
for order in open_orders:
print(order.id, order.email, order.total_price)
# Find orders for a specific customer
customer_orders = shopify.Order.find(customer_id=207119551)
# Get a single order
order = shopify.Order.find(450789469)
print(order.financial_status)
# Close an order
order.close()
print(order.status)
# Re-open an order
order.open()
# Cancel an order
order.cancel(reason="customer", email=True)
# Capture payment
transaction = order.capture(amount="10.00")
print(transaction.status)
# Get transactions for an order
transactions = order.transactions()
for t in transactions:
print(t.kind, t.amount)
```
```
--------------------------------
### API Rate Limits
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Monitor and manage API rate limits using `shopify.Limits` to avoid 429 errors by inspecting call limit status.
```APIDOC
## API Rate Limits — `shopify.Limits`
Inspect the current REST API call limit status from the `X-Shopify-Shop-Api-Call-Limit` response header to avoid 429 rate-limit errors.
```python
import shopify
import time
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Trigger at least one API call to populate headers
shopify.Shop.current()
print(shopify.Limits.credit_used()) # => 1
print(shopify.Limits.credit_limit()) # => 40
print(shopify.Limits.credit_left()) # => 39
# Throttle when close to limit
if shopify.Limits.credit_maxed():
time.sleep(2)
else:
orders = shopify.Order.find(limit=50)
```
```
--------------------------------
### Activate Session
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Activate a session to make authorized API requests.
```APIDOC
## Activate Session
### Description
Activate a shopify session, allowing subsequent API calls to be authenticated with the stored access token.
### Method
```python
session = shopify.Session(shop_url, api_version, access_token)
shopify.ShopifyResource.activate_session(session)
```
### Parameters
- **session** (shopify.Session) - Required - The session object to activate.
```
--------------------------------
### Shopify Cursor-Based Pagination
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Handle large collections using cursor-based pagination with PaginatedCollection and PaginatedIterator. Persist cursors across requests.
```python
import shopify
from shopify import PaginatedIterator
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Basic pagination
page1 = shopify.Product.find(limit=25)
print(f"Page 1: {len(page1)} products")
if page1.has_next_page():
page2 = page1.next_page()
print(f"Page 2: {len(page2)} products")
# Persist pagination cursor across HTTP requests
next_url = page1.next_page_url
# Store next_url in session/cache, then later:
page2 = shopify.Product.find(from_=next_url)
# Memory-efficient iteration over ALL pages
all_products = shopify.Product.find(limit=50)
for page in PaginatedIterator(all_products):
for product in page:
print(product.id, product.title)
# Each page is discarded before the next is fetched
```
--------------------------------
### Retrieve Open Orders with Parameters (REST API)
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Retrieves a list of open orders, limiting the results to 50. This uses the REST API, which is scheduled for deprecation.
```python
new_orders = shopify.Order.find(status="open", limit="50")
```
--------------------------------
### Accessing Prefixed Resources
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
How to access resources that are prefixed by a parent resource, like fulfillments under orders.
```APIDOC
## Accessing Prefixed Resources
### Description
Interacts with resources that are nested under a parent resource, requiring the parent's identifier.
### Method
- `shopify.Fulfillment.find(fulfillment_id, order_id)`: Find a specific fulfillment associated with an order.
### Parameters
#### Path Parameters
- **fulfillment_id** (integer) - Required - The ID of the fulfillment.
- **order_id** (integer) - Required - The ID of the parent order.
### Example Usage
```python
# Note: This REST API example will be deprecated in the future
shopify.Fulfillment.find(255858046, order_id=450789469)
```
```
--------------------------------
### Use Temporary API Session with Context Manager
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Utilize a temporary session within a `with` block for request-scoped operations. The session is automatically activated upon entering the block and restored upon exiting.
```python
import shopify
shopify.Session.setup(api_key="your_api_key", secret="your_api_secret")
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
orders = shopify.Order.find(status="open", limit=10)
for order in orders:
print(order.id, order.total_price)
# Session is automatically restored after the block
```
--------------------------------
### Shopify API Rate Limits
Source: https://context7.com/shopify/shopify_python_api/llms.txt
Monitor and manage API call limits using shopify.Limits to avoid 429 errors. Includes checking credit usage, limit, and remaining credits.
```python
import shopify
import time
with shopify.Session.temp("example-shop.myshopify.com", "2024-10", "shpat_abc123"):
# Trigger at least one API call to populate headers
shopify.Shop.current()
print(shopify.Limits.credit_used()) # => 1
print(shopify.Limits.credit_limit()) # => 40
print(shopify.Limits.credit_left()) # => 39
# Throttle when close to limit
if shopify.Limits.credit_maxed():
time.sleep(2)
else:
orders = shopify.Order.find(limit=50)
```
--------------------------------
### Temporary Session Context
Source: https://github.com/shopify/shopify_python_api/blob/main/README.md
Use a session within a context manager for automatic cleanup.
```APIDOC
## Temporary Session Context
### Description
Manage a Shopify session within a `with` block. The session is automatically activated upon entry and cleared upon exit.
### Method
```python
with shopify.Session.temp(shop_url, api_version, token):
product = shopify.Product.find()
```
### Parameters
- **shop_url** (string) - Required - The shop's myshopify.com URL.
- **api_version** (string) - Required - The Shopify API version to use.
- **token** (string) - Required - The access token for the session.
```