Python API Reference

Python API Reference

#Installation

Current SDK is built with Python3.6. Testing for Python3.6+ will be added soon. If you are interested in using the SDK with the earlier versions of Python (ex: 2.7+), please create a ticket in this repo and let us know :)

#PIP

01pip install magic-admin

#Conda

01conda install magic-admin

#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.

Python
01Magic(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

Python
01from magic_admin import Magic
02
03magic = Magic(
04    api_secret_key='<YOUR_API_SECRET_KEY>'
05    retries=5,
06    timeout=5,
07    backoff_factor=0.01,
08)

#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.

Python
01from magic_admin import Magic
02
03magic = Magic(api_secret_key='sk_live_...')
04
05magic.Token
06magic.Token.get_issuer
07magic.Token.get_public_address
08magic.Token.decode
09magic.Token.validate

#get_issuer

Extracts the iss from the DID Token.

Python
01Token.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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05@user.route('/v1/user/info', method=['GET'])
06def user_info(self):
07    """An exmaple of user info view that uses DID Token to ensure
08    authenticity of a request before returning user info.
09    """
10    did_token = parse_authorization_header_value(
11        requests.headers.get('Authorization'),
12    )
13    if did_token is None:
14        raise BadRequest(
15            'Authorization header is missing or header value is invalid',
16        )
17
18    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
19
20    # Validate the did_token
21    try:
22        magic.Token.validate(did_token)
23        issuer = magic.Token.get_issuer(did_token)
24    except DIDTokenError as e:
25        raise BadRequest('DID Token is invalid: {}'.format(e))
26
27    # Use your application logic to load the user info.
28    user_info = logic.User.load_by(issuer=issuer)
29
30    return HttpResponse(user_info)

#get_public_address

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

Python
01Token.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. 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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05@user.route('/v1/user/info', method=['GET'])
06def user_info(self):
07    """An exmaple of user info view that uses DID Token to ensure
08    authenticity of a request before returning user info.
09    """
10    did_token = parse_authorization_header_value(
11        requests.headers.get('Authorization'),
12    )
13    if did_token is None:
14        raise BadRequest(
15            'Authorization header is missing or header value is invalid',
16        )
17
18    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
19
20    # Validate the did_token.
21    try:
22        magic.Token.validate(did_token)
23        public_address = magic.Token.get_public_address(did_token)
24    except DIDTokenError as e:
25        raise BadRequest('DID Token is invalid: {}'.format(e))
26
27    # Use your application logic to load the user info.
28    user_info = logic.User.load_by(public_address=public_address)
29
30    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.

01Token.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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05# An exmaple of user info view.
06@user.route('/v1/user/info', method=['GET'])
07def user_info(self):
08    """An exmaple of user info view that uses DID Token to ensure
09    authenticity of a request before returning user info.
10    """
11    # Parse the `Authorization` header value for did_token.
12    did_token = parse_authorization_header_value(
13        requests.headers.get('Authorization'),
14    )
15    if did_token is None:
16        raise BadRequest(
17            'Authorization header is missing or header value is invalid',
18        )
19
20    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
21
22    # Validate and decode the token.
23    try:
24        magic.Token.validate(did_token)
25        proof, claim = magic.Token.decode(did_token)
26    except DIDTokenError as e:
27        raise BadRequest('DID Token is malformed: {}'.format(e))
28
29    # You can perform your own validations on the claim fields.
30    if claim['iss'] != 'troll_goat' and claim['aud'] != 'app':
31        raise BadRequest()
32
33    # Use your application logic to load the user info.
34    user_info = logic.User.load_by(issuer=issuer)
35
36    return HttpResponse(user_info)

#validate

Validates a DID token.

01magic.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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05# An exmaple of user info view.
06@user.route('/v1/user/info', method=['GET'])
07def user_info(self):
08    """An exmaple of user info view that uses DID Token to ensure
09    authenticity of a request before returning user info.
10    """
11    # Parse the `Authorization` header value for did_token.
12    did_token = parse_authorization_header_value(
13        requests.headers.get('Authorization'),
14    )
15    if did_token is None:
16        raise BadRequest(
17            'Authorization header is missing or header value is invalid',
18        )
19
20    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
21
22    # Validate the did_token
23    try:
24        magic.Token.validate(did_token)
25        issuer = magic.Token.get_issuer(did_token)
26    except DIDTokenError as e:
27        raise BadRequest('DID Token is invalid: {}'.format(e))
28
29    # Use your application logic to load the user info.
30    user_info = logic.User.load_by(issuer=issuer)
31
32    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.

Python
01from magic_admin import Magic
02
03magic = Magic(api_secret_key='sk_live_...')
04
05magic.User
06magic.User.get_metadata_by_issuer
07magic.User.get_metadata_by_public_address
08magic.User.get_metadata_by_token
09magic.User.logout_by_issuer
10magic.User.logout_by_public_address
11magic.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.

01User.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.

Python
01from magic_admin import Magic
02from magic_admin.error import DIDTokenError
03from magic_admin.error import RequestError
04@user.route('/v1/user/update', method=['POST'])
05def update_user_info(self, user_id):
06    """An exmaple of user update view that uses `iss` stored in the
07    databoase to fresh user metadata.
08    """
09    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
10
11    # User your application logic to get the use data.
12    user_info = logic.User.get_by_id(user_id)
13
14    try:
15        magic_response = magic.User.get_metadata_by_issuer(
16            user_info.issuer,
17        )
18    except RequestError as e:
19        # You can also remap this error to your own application error.
20        return HttpError(str(e))
21
22    if user_info.email != magic_response.data['email']:
23        # Use your application logic to update the user info.
24        logic.User.update_by(
25            user_id,
26            email=magic_response.data['email'],
27        )
28
29    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.

01User.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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05from magic_admin.error import RequestError
06@user.route('/v1/user/update', method=['POST'])
07def update_user_info(self, user_id):
08    """An exmaple of user update view that uses DID Token from the
09    client-side to ensure authenticity of a request before updating
10    the user meta.
11    """
12    did_token = parse_authorization_header_value(
13        requests.headers.get('Authorization'),
14    )
15    if did_token is None:
16        raise BadRequest(
17            'Authorization header is missing or header value is invalid',
18        )
19
20    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
21
22    # Validate the did_token
23    try:
24        magic.Token.validate(did_token)
25        pub_addr = magic.Token.get_public_address(did_token)
26    except DIDTokenError as e:
27        raise BadRequest('DID Token is invalid: {}'.format(e))
28
29    try:
30        magic_response = magic.User.get_metadata_by_public_address(pub_addr)
31    except RequestError as e:
32        # You can also remap this error to your own application error.
33        return HttpError(str(e))
34
35    # Use your application logic to update the user info.
36    user_info = logic.User.update_by(
37        user_id,
38        email=magic_response.data['email'],
39    )
40
41    return HttpResponse(user_info)

#get_metadata_by_token

Retrieves information about the user by the supplied DID Token.

01User.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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05from magic_admin.error import RequestError
06@user.route('/v1/user/update', method=['POST'])
07def update_user_info(self, user_id):
08    # Parse the `Authorization` header value for did_token.
09    did_token = parse_authorization_header_value(
10        requests.headers.get('Authorization'),
11    )
12    if did_token is None:
13        raise BadRequest(
14            'Authorization header is missing or header value is invalid',
15        )
16
17    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
18
19    # Validate the did_token
20    try:
21        magic.Token.validate(did_token)
22    except DIDTokenError as e:
23        raise BadRequest('DID Token is invalid: {}'.format(e))
24
25    try:
26        magic_response = magic.User.get_metadata_by_token(did_token)
27    except RequestError as e:
28        # You can also remap this error to your own application error.
29        return HttpError(str(e))
30
31    # Use your application logic to update the user info.
32    user_info = logic.User.update_by(
33        user_id,
34        email=magic_response.data['email'],
35    )
36
37    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.

01User.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.

Python
01from magic_admin import Magic
02from magic_admin.error import DIDTokenError
03from magic_admin.error import RequestError
04@user.route('/v1/user/logout', method=['POST'])
05def user_logout(self, user_id):
06    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
07
08    # Load user by user_id.
09    user = logic.User.load_by_id(user_id)
10
11    try:
12        magic.User.logout_by_issuer(user.issuer)
13    except RequestError as e:
14        # You can also remap this error to your own application error.
15        return HttpError(str(e))
16
17    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 .

01User.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.

Python
01from magic_admin import Magic
02from magic_admin.error import DIDTokenError
03from magic_admin.error import RequestError
04@user.route('/v1/user/logout', method=['POST'])
05def user_logout(self, user_id):
06    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
07
08    # Load user by user_id.
09    user = logic.User.load_by_id(user_id)
10
11    try:
12        magic.User.logout_by_public_address(user.public_address)
13    except RequestError as e:
14        # You can also remap this error to your own application error.
15        return HttpError(str(e))
16
17    return HttpResponse()

#logout_by_token

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

01User.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.

Python
01from magic_admin import Magic
02# A util provided by `magic_admin` to parse the auth header value.
03from magic_admin.utils.http import parse_authorization_header_value
04from magic_admin.error import DIDTokenError
05from magic_admin.error import RequestError
06@user.route('/v1/user/logout', method=['POST'])
07def user_logout(self, user_id):
08    did_token = parse_authorization_header_value(
09        requests.headers.get('Authorization'),
10    )
11    if did_token is None:
12        raise BadRequest(
13            'Authorization header is missing or header value is invalid',
14        )
15
16    magic = Magic(api_secret_key='<YOUR_API_SECRET_KEY>')
17
18    # Validate the did_token.
19    try:
20        magic.Token.validate(did_token)
21        issuer = magic.Token.get_issuer(did_token)
22    except DIDTokenError as e:
23        raise BadRequest('DID Token is invalid: {}'.format(e))
24
25    # Use your application logic to load the user info.
26    user_info = logic.User.load_by_id(user_id)
27
28    if user_info.issuer != issuer:
29        raise AuthorizationError('You are not authorized for the given ')
30
31    try:
32        magic.User.logout_by_token(did_token)
33    except RequestError as e:
34        # You can also remap this error to your own application error.
35        return HttpError(str(e))
36
37    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.
Python
01from magic_admin.response import MagicResponse
02
03MagicResponse.content
04MagicResponse.status
05MagicResponse.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.

01MagicError
02    |
03    |------- DIDTokenError
04    |
05    |------- RequestError
06                  |
07                  | ------- RateLimitingError
08                  | ------- BadRequestError
09                  | ------- AuthenticationError
10                  | ------- ForbiddenError
11                  | ------- APIError
12                  | ------- APIConnectionError

#MagicError

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

Python
01MagicError(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.

Python
01RequestError(
02    message=None, http_status=None, http_code=None, http_resp_data=None,
03    http_message=None, http_error_code=None, http_request_params=None,
04    http_request_data=None, http_method=None,
05)
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.

Python
01try:
02    # Make requests to Magic server.
03except DIDTokenError as e:
04    pass
05except RateLimitingError as e:
06    pass
07except BadRequestError as e:
08    pass
09except AuthenticationError as e:
10    pass
11except ForbiddenError as e:
12    pass
13except APIError as e:
14    pass
15except APIConnectionError as e:
16    pass

Did you find what you were looking for?