API Reference

Constructor

Magic

The constructor allows you to specify your own API secret key and HTTP request strategy when your application is interacting with the Magic API.

Magic(api_secret_key=None, retries=3, timeout=10, backoff_factor=0.02)

Arguments

  • api_secret_key(str): Your API secret Key retrieved from the Magic Dashboard.
  • retries(num): Total number of retries to allow.
  • timeout(num): A period of time the request is going to wait for a response.
  • backoff_factor(num): A backoff factor to apply between retry attempts.

Returns

  • A Magic object that provides access to all the supported resources.

Examples

from magic_admin import Magic
magic = Magic(
api_secret_key='<YOUR_API_SECRET_KEY>'
retries=5,
timeout=5,
backoff_factor=0.01,
)

Token Resource

The token resource and its methods are accessible on the Magic instance by the Token attribute. It provides methods to interact with the DID Token.

note

The token resource does not make any API calls to the Magic server.

from magic_admin import Magic
magic = Magic(api_secret_key='sk_live_...')
magic.Token
magic.Token.get_issuer
magic.Token.get_public_address
magic.Token.decode
magic.Token.validate

get_issuer

Extracts the iss from the DID Token.

Token.get_issuer(did_token)
Arguments

did_token (str): A DID Token generated by a Magic User on the client-side.

Raises

DIDTokenError if the given DID Token is malformed.

Returns

A Decentralized ID (iss) of the Magic user who generated the DID Token.

Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
@user.route('/v1/user/info', method=['GET'])
def user_info(self):
"""An exmaple of user info view that uses DID Token to ensure
authenticity of a request before returning user info.
"""
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate the did_token
try:
magic.Token.validate(did_token)
issuer = magic.Token.get_issuer(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is invalid: {}'.format(e))
# Use your application logic to load the user info.
user_info = logic.User.load_by(issuer=issuer)
return HttpResponse(user_info)

get_public_address

Gets the cryptographic public address of the Magic User who generated the supplied DID Token.

Token.get_public_address(did_token)
Arguments

did_token (str): A DID Token generated by a Magic user on the client-side.

Raises

DIDTokenError if the given DID Token is malformed.

Returns

A public address of the Magic User who generated the DID Token.

Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
@user.route('/v1/user/info', method=['GET'])
def user_info(self):
"""An exmaple of user info view that uses DID Token to ensure
authenticity of a request before returning user info.
"""
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate the did_token.
try:
magic.Token.validate(did_token)
public_address = magic.Token.get_public_address(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is invalid: {}'.format(e))
# Use your application logic to load the user info.
user_info = logic.User.load_by(public_address=public_address)
return HttpResponse(user_info)

decode

Decodes a DID Token from a Base64 string into a tuple of its individual components: proof and claim. This method allows you decode the DID Token and inspect the token. You can apply your own rules and validations on top of the current Token.validate method.

Token.decode(did_token)
Arguments

did_token (str): A DID Token generated by a Magic user on the client-side.

Raises

DIDTokenError if the given DID Token is malformed.

Returns
  • proof (str): A digital signature that proves the validity of the given claim
  • claim (dict): Unsigned data the user asserts. This should equal the proof after Elliptic Curve recovery. See Decentralized ID Token Specification for fields inside the claim.
Example
important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
# An exmaple of user info view.
@user.route('/v1/user/info', method=['GET'])
def user_info(self):
"""An exmaple of user info view that uses DID Token to ensure
authenticity of a request before returning user info.
"""
# Parse the `Authorization` header value for did_token.
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate and decode the token.
try:
magic.Token.validate(did_token)
proof, claim = magic.Token.decode(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is malformed: {}'.format(e))
# You can perform your own validations on the claim fields.
if claim['iss'] != 'troll_goat' and claim['aud'] != 'app':
raise BadRequest()
# Use your application logic to load the user info.
user_info = logic.User.load_by(issuer=issuer)
return HttpResponse(user_info)

validate

Validates a DID token.

magic.Token.validate(did_token)
Arguments

did_token (str): A DID Token generated by a Magic user on the client-side.

Raises

DIDTokenError if the given DID Token is invalid or malformed.

Returns

None

Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
# An exmaple of user info view.
@user.route('/v1/user/info', method=['GET'])
def user_info(self):
"""An exmaple of user info view that uses DID Token to ensure
authenticity of a request before returning user info.
"""
# Parse the `Authorization` header value for did_token.
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate the did_token
try:
magic.Token.validate(did_token)
issuer = magic.Token.get_issuer(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is invalid: {}'.format(e))
# Use your application logic to load the user info.
user_info = logic.User.load_by(issuer=issuer)
return HttpResponse(user_info)

User Resource

The user resource and its methods are accessible on the Magic instance by the User attribute. It provides methods to interact with the User.

from magic_admin import Magic
magic = Magic(api_secret_key='sk_live_...')
magic.User
magic.User.get_metadata_by_issuer
magic.User.get_metadata_by_public_address
magic.User.get_metadata_by_token
magic.User.logout_by_issuer
magic.User.logout_by_public_address
magic.User.logout_by_token

get_metadata_by_issuer

Retrieves information about the user by the supplied iss from the DID Token. This method is useful if you store the iss with your user data, which is recommended.

User.get_metadata_by_issuer(issuer)
Arguments

issuer (str): The user's Decentralized ID, which can be parsed using Token.get_issuer

Raises
  • RateLimitingError: If you have sent too many requests within a given period of time.
  • BadRequestError: If the supplied parameters are invalid.
  • AuthenticationError: If your API secret key cannot be authenticated with Magic API server.
  • ForbiddenError: If your API secret key is not authorized to access the resources.
  • APIError: For any other API error.
  • APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns
  • A MagicResponse: The data field contains all of the user meta information.
    • issuer (str): The user's Decentralized ID.
    • email (str): The user's email address.
    • public_address (str): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

from magic_admin import Magic
from magic_admin.error import DIDTokenError
from magic_admin.error import RequestError
@user.route('/v1/user/update', method=['POST'])
def update_user_info(self, user_id):
"""An exmaple of user update view that uses `iss` stored in the
databoase to fresh user metadata.
"""
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# User your application logic to get the use data.
user_info = logic.User.get_by_id(user_id)
try:
magic_response = magic.User.get_metadata_by_issuer(
user_info.issuer,
)
except RequestError as e:
# You can also remap this error to your own application error.
return HttpError(str(e))
if user_info.email != magic_response.data['email']:
# Use your application logic to update the user info.
logic.User.update_by(
user_id,
email=magic_response.data['email'],
)
return HttpResponse()

get_metadata_by_public_address

Retrieves information about the user by the supplied public_address. This method is useful if you store the public_address with your user data.

User.get_metadata_by_public_address(public_address)
Arguments

public_address (str): The user's Ethereum public address, which can be parsed using Token.get_public_address.

Raises
  • RateLimitingError: If you have sent too many requests within a given period of time.
  • BadRequestError: If the supplied parameters are invalid.
  • AuthenticationError: If your API secret key cannot be authenticated with Magic API server.
  • ForbiddenError: If your API secret key is not authorized to access the resources.
  • APIError: For any other API error.
  • APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns
  • A MagicResponse: The data field contains all of the user meta information.
    • issuer (str): The user's Decentralized ID.
    • email (str): The user's email address.
    • public_address (str): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
from magic_admin.error import RequestError
@user.route('/v1/user/update', method=['POST'])
def update_user_info(self, user_id):
"""An exmaple of user update view that uses DID Token from the
client-side to ensure authenticity of a request before updating
the user meta.
"""
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate the did_token
try:
magic.Token.validate(did_token)
pub_addr = magic.Token.get_public_address(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is invalid: {}'.format(e))
try:
magic_response = magic.User.get_metadata_by_public_address(pub_addr)
except RequestError as e:
# You can also remap this error to your own application error.
return HttpError(str(e))
# Use your application logic to update the user info.
user_info = logic.User.update_by(
user_id,
email=magic_response.data['email'],
)
return HttpResponse(user_info)

get_metadata_by_token

Retrieves information about the user by the supplied DID Token.

User.get_metadata_by_token(did_token)
Arguments

did_token (str): A DID Token generated by a Magic User on the client-side.

Raises
  • RateLimitingError: If you have sent too many requests within a given period of time.
  • BadRequestError: If the supplied parameters are invalid.
  • AuthenticationError: If your API secret key cannot be authenticated with Magic API server.
  • ForbiddenError: If your API secret key is not authorized to access the resources.
  • APIError: For any other API error.
  • APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns
  • A MagicResponse: The data field contains all of the user meta information.
    • issuer (str): The user's Decentralized ID.
    • email (str): The user's email address.
    • public_address (str): The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
from magic_admin.error import RequestError
@user.route('/v1/user/update', method=['POST'])
def update_user_info(self, user_id):
# Parse the `Authorization` header value for did_token.
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate the did_token
try:
magic.Token.validate(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is invalid: {}'.format(e))
try:
magic_response = magic.User.get_metadata_by_token(did_token)
except RequestError as e:
# You can also remap this error to your own application error.
return HttpError(str(e))
# Use your application logic to update the user info.
user_info = logic.User.update_by(
user_id,
email=magic_response.data['email'],
)
return HttpResponse(user_info)

logout_by_issuer

Logs a user out of all Magic SDK sessions given the user's Decentralized ID (iss). This method is useful if you store the iss with your user data, which is recommended.

User.logout_by_issuer(issuer)
Arguments

issuer (str): The user's Decentralized ID, which can be parsed using Token.get_issuer

Raises
  • RateLimitingError: If you have sent too many requests within a given period of time.
  • BadRequestError: If the supplied parameters are invalid.
  • AuthenticationError: If your API secret key cannot be authenticated with Magic API server.
  • ForbiddenError: If your API secret key is not authorized to access the resources.
  • APIError: For any other API error.
  • APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns

A MagicResponse.

Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

from magic_admin import Magic
from magic_admin.error import DIDTokenError
from magic_admin.error import RequestError
@user.route('/v1/user/logout', method=['POST'])
def user_logout(self, user_id):
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Load user by user_id.
user = logic.User.load_by_id(user_id)
try:
magic.User.logout_by_issuer(user.issuer)
except RequestError as e:
# You can also remap this error to your own application error.
return HttpError(str(e))
return HttpResponse()

logout_by_public_address

Logs a user out of all Magic SDK sessions given the user's public address. This method is useful if you store the public_address .

User.logout_by_public_address(public_address)
Arguments

public_address (str): The user's Ethereum public address.

Raises
  • RateLimitingError: If you have sent too many requests within a given period of time.
  • BadRequestError: If the supplied parameters are invalid.
  • AuthenticationError: If your API secret key cannot be authenticated with Magic API server.
  • ForbiddenError: If your API secret key is not authorized to access the resources.
  • APIError: For any other API error.
  • APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns

A MagicResponse.

Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

from magic_admin import Magic
from magic_admin.error import DIDTokenError
from magic_admin.error import RequestError
@user.route('/v1/user/logout', method=['POST'])
def user_logout(self, user_id):
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Load user by user_id.
user = logic.User.load_by_id(user_id)
try:
magic.User.logout_by_public_address(user.public_address)
except RequestError as e:
# You can also remap this error to your own application error.
return HttpError(str(e))
return HttpResponse()

logout_by_token

Logs a user out of all Magic SDK sessions given the DID Token.

User.logout_by_token(did_token)
Arguments

did_token (str): A DID Token generated by a Magic user on the client-side.

Raises
  • RateLimitingError: If you have sent too many requests within a given period of time.
  • BadRequestError: If the supplied parameters are invalid.
  • AuthenticationError: If your API secret key cannot be authenticated with Magic API server.
  • ForbiddenError: If your API secret key is not authorized to access the resources.
  • APIError: For any other API error.
  • APIConnectionError: If your server cannot communicate with the Magic server. Normally this is a network communication error.
note

See Error Handling for more examples.

Returns

A MagicResponse.

Example

The example below is assuming you are already using a Python Web Framework (Django, Flask, Cherrypy, etc.) Web framework's specific imports are omitted in favor of the simplicity of the example. Only the magic_admin related imports are shown below.

important

It is important to always validate the DID Token before using.

from magic_admin import Magic
# A util provided by `magic_admin` to parse the auth header value.
from magic_admin.utils.http import parse_authorization_header_value
from magic_admin.error import DIDTokenError
from magic_admin.error import RequestError
@user.route('/v1/user/logout', method=['POST'])
def user_logout(self, user_id):
did_token = parse_authorization_header_value(
requests.headers.get('Authorization'),
)
if did_token is None:
raise BadRequest(
'Authorization header is missing or header value is invalid',
)
magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
# Validate the did_token.
try:
magic.Token.validate(did_token)
issuer = magic.Token.get_issuer(did_token)
except DIDTokenError as e:
raise BadRequest('DID Token is invalid: {}'.format(e))
# Use your application logic to load the user info.
user_info = logic.User.load_by_id(user_id)
if user_info.issuer != issuer:
raise AuthorizationError('You are not authorized for the given ')
try:
magic.User.logout_by_token(did_token)
except RequestError as e:
# You can also remap this error to your own application error.
return HttpError(str(e))
return HttpResponse()

Response and Error Handling

Response

There is only one response object that will be returned from a successful API call

MagicResponse

This is the interface to interact Magic API responses. It will only be returned if the API request status code is between 200 (inclusive) and 300 (exclusive).

You will have access to the following attributes:

  • content (bytes): Raw content returned by the API response.
  • status_code (num): HTTP status code for the given request.
  • data (dict): Parsed content.
from magic_admin.response import MagicResponse
MagicResponse.content
MagicResponse.status
MagicResponse.data

Errors

The conventional HTTP response is adopted by the SDK. For the status code in :

  • 2XX - Indicates success
  • 4XX - Indicates client errors. Information provided to the SDK is invalid.
  • 5XX - Indicates server errors

Below is the error class inheritance which can help developers to programmatically handle the error cases.

MagicError
|
|------- DIDTokenError
|
|------- RequestError
|
| ------- RateLimitingError
| ------- BadRequestError
| ------- AuthenticationError
| ------- ForbiddenError
| ------- APIError
| ------- APIConnectionError

MagicError

This is the base class of all the Magic SDK errors.

MagicError(message=None)

DIDTokenError

Any DID Token related error. This can mean the given token is malformed or invalid.

RequestError

This is the base class of all the Magic API request errors. This error class will provide details of unsuccessful API requests.

RequestError(
message=None, http_status=None, http_code=None, http_resp_data=None,
http_message=None, http_error_code=None, http_request_params=None,
http_request_data=None, http_method=None,
)
CodeErrorDescription
429RateLimitingErrorToo many requests are submitted for a given period of time.
400BadRequestErrorThe API requests might have missing required fields or bad inputs.
401AuthenticationErrorThis means your API secret key is invalid.
403ForbiddenErrorThis normally means the given API secret key doesn't have permission to perform the action on the given resources.
โ€“APIErrorThis is a generic API error that handlers other status codes that are not explicitly handled. Ex: 500 , 404 , etc.
โ€“APIConnectionErrorNetwork connection error. This normally means the connection between between your application and Magic API server cannot be established.

Error Handling

It is recommended to handle the API errors gracefully.

try:
# Make requests to Magic server.
except DIDTokenError as e:
pass
except RateLimitingError as e:
pass
except BadRequestError as e:
pass
except AuthenticationError as e:
pass
except ForbiddenError as e:
pass
except APIError as e:
pass
except APIConnectionError as e:
pass