Overview
The Magic package for Python is your entry-point to secure, passwordless authentication for your application. This guide will cover some important topics for getting started with Magic Python package and to make the most of Magic’s features.Getting Started
The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic secret key.Installation
The Magic Admin Python SDK requires Python 3.11 or higher.Constructor
Magic()
Parameter | Type | Definition |
api_secret_key | str | Your secret API Key retrieved from the Magic Dashboard. |
client_id? | str | Your Magic client ID. If not provided, will be fetched automatically. |
retries? | num | Total number of retries to allow. Default: 3. |
timeout? | num | A period of time the request is going to wait for a response. Default: 10. |
backoff_factor? | num | A backoff factor to apply between retry attempts. Default: 0.02. |
Initialization
Initialize Magic instance.Python
Token Resource
The token resource and its methods are accessible on the Magic instance by theToken
attribute. It provides methods to interact with the DID Token.
The token resource does not make any API calls to the Magic server.
get_issuer
Extracts the iss
from the DID Token.
Python
did_token
(str): A DID Token generated by a Magic User on the client-side
DIDTokenMalformed
if the given DID Token is malformed
- A Decentralized ID (
iss
) of the Magic user who generated the DID Token
get_public_address
Gets the cryptographic public address of the Magic User who generated the supplied DID Token.
Python
did_token
(str): A DID Token generated by a Magic user on the client-side
DIDTokenMalformed
if the given DID Token is malformed
- A public address of the Magic User who generated the DID Token. Currently, this value is associated with the Ethereum blockchain.
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.
Python
did_token
(str): A DID Token generated by a Magic user on the client-side
DIDTokenMalformed
if the given DID Token is malformed
proof
(str): A digital signature that proves the validity of the givenclaim
claim
(dict): Unsigned data the user asserts. This should equal theproof
after Elliptic Curve recovery. See Decentralized ID Token Specification for fields inside theclaim
.
validate
Validates a DID token.
Python
did_token
(str): A DID Token generated by a Magic user on the client-side
DIDTokenMalformed
if the given DID Token is malformedDIDTokenInvalid
if the given DID Token is invalid
- None.
User Resource
The user resource and its methods are accessible on the Magic instance by theUser
attribute. It provides methods to interact with the User.
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.
Python
issuer
(str): The user’s Decentralized ID, which can be parsed using Token.get_issuer
RateLimitingError
: If you have sent too many requests within a given period of timeBadRequestError
: If the supplied parameters are invalidAuthenticationError
: If your API secret key cannot be authenticated with Magic API serverForbiddenError
: If your API secret key is not authorized to access the resourcesAPIError
: For any other API errorAPIConnectionError
: If your server cannot communicate with the Magic server. Normally this is a network communication error.
See Error Handling for more examples.
- A
MagicResponse
: Thedata
field contains all of the user meta information.issuer
(str): The user’s Decentralized IDpublic_address
(str): The authenticated user’s public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.email
(str): The user’s email addressphone_number
(str): The user’s phone numberoauth_provider
(str): OAuth provider, if anywallets
(arr): Array of user’s wallet addresses
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.
Python
public_address
(str): The user’s Ethereum public address, which can be parsed using Token.get_public_address
RateLimitingError
: If you have sent too many requests within a given period of time.BadRequestError
: If the supplied parameters are invalidAuthenticationError
: If your API secret key cannot be authenticated with Magic API serverForbiddenError
: If your API secret key is not authorized to access the resourcesAPIError
: For any other API errorAPIConnectionError
: If your server cannot communicate with the Magic server. Normally this is a network communication error.
See Error Handling for more examples.
- A
MagicResponse
: Thedata
field contains all of the user meta information.issuer
(str): The user’s Decentralized IDpublic_address
(str): The authenticated user’s public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.email
(str): The user’s email addressphone_number
(str): The user’s phone numberoauth_provider
(str): OAuth provider, if anywallets
(arr): Array of user’s wallet addresses
get_metadata_by_token
Retrieves information about the user by the supplied DID Token.
Python
did_token
(str): A DID Token generated by a Magic User on the client-side.
RateLimitingError
: If you have sent too many requests within a given period of timeBadRequestError
: If the supplied parameters are invalidAuthenticationError
: If your API secret key cannot be authenticated with Magic API serverForbiddenError
: If your API secret key is not authorized to access the resourcesAPIError
: For any other API errorAPIConnectionError
: If your server cannot communicate with the Magic server. Normally this is a network communication error.
See Error Handling for more examples.
- A
MagicResponse
: Thedata
field contains all of the user meta information.issuer
(str): The user’s Decentralized IDpublic_address
(str): The authenticated user’s public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.email
(str): The user’s email addressphone_number
(str): The user’s phone numberoauth_provider
(str): OAuth provider, if anywallets
(arr): Array of user’s wallet addresses
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.
Python
issuer
(str): The user’s Decentralized ID, which can be parsed using Token.get_issuer
RateLimitingError
: If you have sent too many requests within a given period of timeBadRequestError
: If the supplied parameters are invalidAuthenticationError
: If your API secret key cannot be authenticated with Magic API serverForbiddenError
: If your API secret key is not authorized to access the resourcesAPIError
: For any other API errorAPIConnectionError
: If your server cannot communicate with the Magic server. Normally this is a network communication error.
See Error Handling for more examples.
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
.
Python
public_address
(str): The user’s Ethereum public address
RateLimitingError
: If you have sent too many requests within a given period of timeBadRequestError
: If the supplied parameters are invalidAuthenticationError
: If your API secret key cannot be authenticated with Magic API serverForbiddenError
: If your API secret key is not authorized to access the resourcesAPIError
: For any other API errorAPIConnectionError
: If your server cannot communicate with the Magic server. Normally this is a network communication error.
See Error Handling for more examples.
logout_by_token
Logs a user out of all Magic SDK sessions given the DID Token.
Python
did_token
(str): A DID Token generated by a Magic user on the client-side
RateLimitingError
: If you have sent too many requests within a given period of timeBadRequestError
: If the supplied parameters are invalidAuthenticationError
: If your API secret key cannot be authenticated with Magic API serverForbiddenError
: If your API secret key is not authorized to access the resourcesAPIError
: For any other API errorAPIConnectionError
: If your server cannot communicate with the Magic server. Normally this is a network communication error.
See Error Handling for more examples.
Utils Resource
The utils resource provides utility methods for common operations like parsing authorization headers and validating token ownership for NFT gating.parse_authorization_header
Extracts a DID token from an HTTP Authorization header.
Python
header
(str): The Authorization header string inBearer {token}
format
ExpectedBearerStringError
: If header is not in the expected format
str
: The DID token extracted from the header
Python
validate_token_ownership
Validates that a user owns a specific NFT token for token gating functionality.
Python
did_token
(str): The DID token to validatecontract_address
(str): The smart contract address of the NFTcontract_type
(str): Either'ERC721'
or'ERC1155'
rpc_url
(str): The RPC endpoint URL for the blockchaintoken_id
(str, optional): Required for ERC1155 contracts
ValueError
: If ERC1155 is specified without token_idException
: If DID token validation fails
dict
: Response with validation resultvalid
(bool): Whether the user owns the tokenerror_code
(str): Error code if validation failsmessage
(str): Human-readable error message
Python
WalletType Enum
TheWalletType
enum provides support for multiple blockchain networks.
Supported Networks
- EVM Compatible: ETH, AVAX, CELO, HARMONY, ICON, ZILLIQA, HEDERA, CONFLUX, TERRA, TAQUITO, ED
- Non-EVM: SOLANA, POLKADOT, NEAR, FLOW, TEZOS, COSMOS, ALGOD, BITCOIN, HELIUM
Multi-Chain User Metadata
The User resource supports retrieving metadata for specific wallet types across different blockchains.get_metadata_by_issuer_and_wallet
Retrieves user metadata for a specific wallet type by issuer.
Python
issuer
(str): The user’s Decentralized IDwallet_type
(WalletType): The specific wallet type to query
- A
MagicResponse
: Thedata
field contains user metadata for the specified wallet type
get_metadata_by_public_address_and_wallet
Retrieves user metadata for a specific wallet type by public address.
Python
public_address
(str): The user’s public addresswallet_type
(WalletType): The specific wallet type to query
- A
MagicResponse
: Thedata
field contains user metadata for the specified wallet type
get_metadata_by_token_and_wallet
Retrieves user metadata for a specific wallet type by DID token.
Python
did_token
(str): A DID Token generated by a Magic userwallet_type
(WalletType): The specific wallet type to query
- A
MagicResponse
: Thedata
field contains user metadata for the specified wallet type
Python
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 responsestatus_code
(num): HTTP status code for the given requestdata
(dict): Parsed content
Python
Errors
The conventional HTTP response is adopted by the SDK. For the status code in:2XX
- Indicates success4XX
- Indicates client errors. Information provided to the SDK is invalid.5XX
- Indicates server errors
MagicError
This is the base class of all the Magic SDK errors.Python
RequestError
This is the base class of all the Magic API request errors. This error class will provide details of unsuccessful API requests.Python
Code | Error | Description |
429 | RateLimitingError | Too many requests are submitted for a given period of time. |
400 | BadRequestError | The API requests might have missing required fields or bad inputs. |
401 | AuthenticationError | This means your API secret key is invalid. |
403 | ForbiddenError | This normally means the given API secret key doesn’t have permission to perform the action on the given resources. |
– | APIError | This is a generic API error that handles other status codes that are not explicitly handled. Ex: 500 , 404 , etc. |
– | APIConnectionError | Network connection error. This normally means the connection between between your application and Magic API server cannot be established. |
DIDTokenInvalid
This means the given token fails the validation.DIDTokenMalformed
This means the given token format is invalid.DIDTokenExpired
This means the given token has expired.ExpectedBearerStringError
This means the Authorization header is not in the expectedBearer {token}
format.
Error Handling
It is recommended to implement error handling for API responses.Python