Skip to content
This repository was archived by the owner on Oct 6, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 18 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@ To easily install or upgrade to the latest release, use [pip](http://www.pip-ins
pip install --upgrade ShopifyAPI
```

### Table of Contents

- [Getting Started](#getting-started)
- [Public and Custom Apps](#public-and-custom-apps)
- [Private Apps](#private-apps)
- [Billing](#billing)
- [Session Tokens](docs/session-tokens)
- [Handling Access Scope Operations](docs/api-access.md)
- [Advanced Usage](#advanced-usage)
- [Prefix Options](#prefix-options)
- [Console](#console)
- [GraphQL](#graphql)
- [Using Development Version](#using-development-version)
- [Relative Cursor Pagination](#relative-cursor-pagination)
- [Limitations](#limitations)
- [Additional Resources](#additional-resources)

Comment thread
NabeelAhsen marked this conversation as resolved.
Resolved

### Getting Started
#### Public and Custom Apps

Expand Down Expand Up @@ -120,61 +138,6 @@ _Note: Your application must be public to test the billing process. To test on a
has_been_billed = activated_charge.status == 'active'
```

### Session tokens

The Shopify Python API library provides helper methods to decode [session tokens](https://shopify.dev/concepts/apps/building-embedded-apps-using-session-tokens). You can use the `decode_from_header` function to extract and decode a session token from an HTTP Authorization header.

#### Basic usage

```python
from shopify import session_token

decoded_payload = session_token.decode_from_header(
authorization_header=your_auth_request_header,
api_key=your_api_key,
secret=your_api_secret,
)
```

#### Create a decorator using `session_token`

Here's a sample decorator that protects your app views/routes by requiring the presence of valid session tokens as part of a request's headers.

```python
from shopify import session_token


def session_token_required(func):
def wrapper(*args, **kwargs):
request = args[0] # Or flask.request if you use Flask
try:
decoded_session_token = session_token.decode_from_header(
authorization_header = request.headers.get('Authorization'),
api_key = SHOPIFY_API_KEY,
secret = SHOPIFY_API_SECRET
)
with shopify_session(decoded_session_token):
return func(*args, **kwargs)
except session_token.SessionTokenError as e:
# Log the error here
return unauthorized_401_response()

return wrapper


def shopify_session(decoded_session_token):
shopify_domain = decoded_session_token.get("dest")
access_token = get_offline_access_token_by_shop_domain(shopify_domain)

return shopify.Session.temp(shopify_domain, SHOPIFY_API_VERSION, access_token)


@session_token_required # Requests to /products require session tokens
def products(request):
products = shopify.Product.find()
...
```

### Advanced Usage
It is recommended to have at least a basic grasp on the principles of the [pyactiveresource](https://github.com/Shopify/pyactiveresource) library, which is a port of rails/ActiveResource to Python and upon which this package relies heavily.

Expand Down
73 changes: 73 additions & 0 deletions docs/api-access.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Handling access scope operations

#### Table of contents

- [Common ApiAccess operations](#common-apiaccess-operations)
- [Using ApiAccess to handle changes in app access scopes](#using-apiaccess-to-handle-changes-in-app-access-scopes)

There are common operations that are used for managing [access scopes](https://shopify.dev/docs/admin-api/access-scopes) in apps. Such operations include serializing, deserializing and normalizing scopes. Other operations can include checking whether two sets of scopes grant the same API access or whether one set covers the access granted by another set.

To encapsulate the access granted by access scopes, you can use the `ApiAccess` value object.

## Common ApiAccess operations

### Constructing an ApiAccess

```python
api_access = ApiAccess(["read_products", "write_orders"]) # List of access scopes
another_api_access = ApiAccess("read_products, write_products, unauthenticated_read_themes") # String of comma-delimited access scopes
```

### Serializing ApiAccess

```python
api_access = ApiAccess(["read_products", "write_orders", "unauthenticated_read_themes"])

access_scopes_list = list(api_access) # ["read_products", "write_orders", "unauthenticated_read_themes"]
comma_delmited_access_scopes = str(api_access) # "read_products,write_orders,unauthenticated_read_themes"
```

### Comparing ApiAccess objects

#### Checking for API access equality

```python
expected_api_access = ApiAccess(["read_products", "write_orders"])

actual_api_access = ApiAccess(["read_products", "read_orders", "write_orders"])
non_equal_api_access = ApiAccess(["read_products", "write_orders", "read_themes"])

actual_api_access == expected_api_access # True
non_equal_api_access == expected_api_access # False
```

#### Checking if ApiAccess covers the access of another

```python
superset_access = ApiAccess(["write_products", "write_orders", "read_themes"])
subset_access = ApiAccess(["read_products", "write_orders"])

superset_access.covers(subset_access) # True
```

## Using ApiAccess to handle changes in app access scopes

If your app has changes in the access scopes it requests, you can use the `ApiAccess` object to determine whether the merchant needs to go through OAuth based on the scopes currently granted. A sample decorator shows how this can be achieved when loading an app.

```python
from shopify import ApiAccess


def oauth_on_access_scopes_mismatch(func):
def wrapper(*args, **kwargs):
shop_domain = get_shop_query_paramer(request) # shop query param when loading app
current_shop_scopes = ApiAccess(ShopStore.get_record(shopify_domain = shop_domain).access_scopes)
expected_access_scopes = ApiAccess(SHOPIFY_API_SCOPES)

if current_shop_scopes != expected_access_scopes:
return redirect_to_login() # redirect to OAuth to update access scopes granted

return func(*args, **kwargs)

return wrapper
```
54 changes: 54 additions & 0 deletions docs/session-tokens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Session tokens

The Shopify Python API library provides helper methods to decode [session tokens](https://shopify.dev/concepts/apps/building-embedded-apps-using-session-tokens). You can use the `decode_from_header` function to extract and decode a session token from an HTTP Authorization header.

## Basic usage

```python
from shopify import session_token

decoded_payload = session_token.decode_from_header(
authorization_header=your_auth_request_header,
api_key=your_api_key,
secret=your_api_secret,
)
```

## Create a decorator using `session_token`

Here's a sample decorator that protects your app views/routes by requiring the presence of valid session tokens as part of a request's headers.

```python
from shopify import session_token


def session_token_required(func):
def wrapper(*args, **kwargs):
request = args[0] # Or flask.request if you use Flask
try:
decoded_session_token = session_token.decode_from_header(
authorization_header = request.headers.get('Authorization'),
api_key = SHOPIFY_API_KEY,
secret = SHOPIFY_API_SECRET
)
with shopify_session(decoded_session_token):
return func(*args, **kwargs)
except session_token.SessionTokenError as e:
# Log the error here
return unauthorized_401_response()

return wrapper


def shopify_session(decoded_session_token):
shopify_domain = decoded_session_token.get("dest")
access_token = get_offline_access_token_by_shop_domain(shopify_domain)

return shopify.Session.temp(shopify_domain, SHOPIFY_API_VERSION, access_token)


@session_token_required # Requests to /products require session tokens
def products(request):
products = shopify.Product.find()
...
```
1 change: 1 addition & 0 deletions shopify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
from shopify.resources import *
from shopify.limits import Limits
from shopify.api_version import *
from shopify.api_access import *
from shopify.collection import PaginatedIterator
52 changes: 52 additions & 0 deletions shopify/api_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import re


class ApiAccessError(Exception):
pass


class ApiAccess:

SCOPE_DELIMITER = ","
SCOPE_RE = re.compile(r"\A(?P<unauthenticated>unauthenticated_)?(write|read)_(?P<resource>.*)\Z")
IMPLIED_SCOPE_RE = re.compile(r"\A(?P<unauthenticated>unauthenticated_)?write_(?P<resource>.*)\Z")

def __init__(self, scopes):
if type(scopes) == str:
scopes = scopes.split(self.SCOPE_DELIMITER)

self.__store_scopes(scopes)

def covers(self, api_access):
return api_access._compressed_scopes <= self._expanded_scopes

def __str__(self):
return self.SCOPE_DELIMITER.join(self._compressed_scopes)

def __iter__(self):
return iter(self._compressed_scopes)

def __eq__(self, other):
return type(self) == type(other) and self._compressed_scopes == other._compressed_scopes

def __store_scopes(self, scopes):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just out of curiosity what do double leading underscores do? 😅 Is this for name mangling?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the Python convention of defining "private" methods. Although, methods in Python cannot be truly private. This is just a way to indicate that this method should not be consumed as a public interface as it is more likely to change.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohh okay makes sense!

sanitized_scopes = frozenset(filter(None, [scope.strip() for scope in scopes]))
self.__validate_scopes(sanitized_scopes)

implied_scopes = frozenset(self.__implied_scope(scope) for scope in sanitized_scopes)
self._compressed_scopes = sanitized_scopes - implied_scopes
self._expanded_scopes = sanitized_scopes.union(implied_scopes)

def __validate_scopes(self, scopes):
for scope in scopes:
if not self.SCOPE_RE.match(scope):
error_message = "'{s}' is not a valid access scope".format(s=scope)
raise ApiAccessError(error_message)

def __implied_scope(self, scope):
match = self.IMPLIED_SCOPE_RE.match(scope)
if match:
return "{unauthenticated}read_{resource}".format(
unauthenticated=match.group("unauthenticated") or "",
resource=match.group("resource"),
)
Loading