Package: accelbyte-py-sdk
AccelByte Python SDKA software development kit (SDK) for interacting with AccelByte services written in Python.This SDK was generated from OpenAPI specification documents included in thespecdirectory.SetupThis SDK requires Python 3.9 to be installed.Install with PipInstall dependencies.pipinstallrequestshttpxwebsocketsPyYAMLPyJWT[crypto]mmh3bitarrayInstall from PyPIpipinstallaccelbyte-py-sdkor install from source.pipinstallgit+https://github.com/AccelByte/accelbyte-python-sdk.git@{VERSION}#egg=accelbyte_py_sdkReplace{VERSION}with a specific release version tag. When starting a new project,
using the latest release version is recommended. For the list of available versions, seereleases.Special note only for Windows environmentIf you encounter errorpath too longwhen attempting to install the SDK. The steps to solve this are:Enable long paths in registry.Enable long paths in git.git config --global core.longpaths trueRestart the powershell window you used to take effect.Try installing SDK again.pip install git+https://github.com/AccelByte/accelbyte-python-sdk.git@{VERSION}#egg=accelbyte_py_sdkEnvironment VariablesThe following environment variables need to be set when usingEnvironmentConfigRepository(default).NameRequiredExampleAB_BASE_URLYeshttps://demo/accelbyte.ioAB_CLIENT_IDYesabcdef0123456789abcdef0123456789AB_CLIENT_SECRETYes, only if you use a privateAB_CLIENT_IDab#c,d)ef(ab#c,d)ef(ab#c,d)ef(abAB_NAMESPACEYes, the SDK will automatically fill up the{namespace}path parameter (overridable)accelbyteAB_APP_NAMENo, the SDK will automatically fill up theUser-Agentheader (overridable)MyAppAB_APP_VERSIONNo, the SDK will automatically fill up theUser-Agentheader (overridable)1.0.0UsageInitializingYou'll have to initialize the SDK using theinitialize()function.importaccelbyte_py_sdkif__name__=="__main__":accelbyte_py_sdk.initialize()# uses EnvironmentConfigRepository by default#   which in turn uses '$AB_BASE_URL', '$AB_CLIENT_ID', '$AB_CLIENT_SECRET', '$AB_NAMESPACE'You could also pass in options like so:fromosimportenvironimportaccelbyte_py_sdkfromaccelbyte_py_sdk.coreimportMyConfigRepositoryif__name__=="__main__":base_url=environ["MY_BASE_URL"]client_id=environ["MY_CLIENT_ID"]client_secret=environ["MY_CLIENT_SECRET"]namespace=environ["MY_NAMESPACE"]app_name=environ["MY_APP_NAME"]app_version=environ["MY_APP_VERSION"]my_config_repository=MyConfigRepository(base_url=base_url,client_id=client_id,client_secret=client_secret,namespace=namespace,app_name=app_name,app_version=app_version)options={"config":my_config_repository}accelbyte_py_sdk.initialize(options)# you could still set some of these options after initializing.# ex. accelbyte_py_sdk.core.set_config_repository(my_config_repository)Logging In and Logging OutLogin using Username and Passwordfromosimportenvironimportaccelbyte_py_sdkfromaccelbyte_py_sdk.services.authimportlogin_user,logoutif__name__=="__main__":accelbyte_py_sdk.initialize()username=environ["AB_USERNAME"]password=environ["AB_PASSWORD"]token,error=login_user(username,password)asserterrorisNone_,error=logout()asserterrorisNoneHerelogin_user(username, password)andlogout()are wrapper functions.You can also specify the scope you want forlogin_user(...). With thescopeparameter typed asOptional[Union[str, List[str]]]. By default the scope used iscommerce account social publishing analytics(a space seprated value string).login_user(username,password,scope="scopeA")# login_user(username, password, scope="scopeA scopeB")  # space separated values# login_user(username, password, scope=["scopeA", "scopeB"])Login using OAuth Client (Public or Confidential)fromosimportenvironimportaccelbyte_py_sdkfromaccelbyte_py_sdk.services.authimportlogin_clientif__name__=="__main__":accelbyte_py_sdk.initialize()client_id=environ["AB_CLIENT_ID"]client_secret=environ["AB_CLIENT_SECRET"]token,error=login_client(client_id,client_secret)# passing '$AB_CLIENT_ID' and '$AB_CLIENT_SECRET' is same as:# token, error = login_client()asserterrorisnotNone:bulb: The use of a Public OAuth Client is highly discouraged for this use case. Please ensure that you both set the Client ID and Client Secret.Refreshing Tokens:bulb: Usinglogin_x(..., auto_refresh=True)automatically refreshes the token once the expiration draws near.# set the refresh rate for 'login_client'# 0.5 means refresh when we 50% of the expiration duration has passedres,err=login_client(client_id,client_secret,auto_refresh=True,refresh_rate=0.5)# set the refresh rate for 'login_user'# 0.5 means refresh when we 50% of the expiration duration has passedres,err=login_user(username,password,auto_refresh=True,refresh_rate=0.5)The auto refresh is only triggered when another request is fired. If you want to the refresh run automatically in the background. Use any of theLoginXTimerclasses.fromaccelbyte_py_sdk.services.authimportLoginClientTimer,LoginPlatformTimer,LoginUserTimer,RefreshLoginTimerres,err=login_user(username,password)iferrisnotNone:exit(1)# creates a threading.Timer-like object that calls login_user every 1800 seconds repeatedly 'inf' timesinterval=1800timer=LoginUserTimer(interval,username=username,password=password,repeats=-1,# <0: repeat 'inf' times | 0 or None: repeat 0 times | >0: repeat n timesautostart=True,)To manually refresh the token:fromaccelbyte_py_sdk.coreimportget_token_repositoryfromaccelbyte_py_sdk.services.authimportrefresh_logintoken_repo=get_token_repository()refresh_token=token_repo.get_refresh_token()token,error=refresh_login(refresh_token)asserterrorisNoneTo use on-demand token refresh, enable therefresh_if_possibleoption by setting it to True.
This configuration involves checking for the presence of an existing token, verifying its expiration status.
If the token has expired, the SDK will then examine whether a refresh token exists.
If a refresh token is available, it will be utilized to obtain a new token.res,error=login_user(username,password,refresh_if_possible=True)Using multiple SDK instancesThe examples above demonstrates using just one instance of the Python SDK (the default which is also global), but you could also instantiate multiple instances of the SDK and use them at the same time.importaccelbyte_py_sdk.services.authasauth_serviceimportaccelbyte_py_sdk.api.iamasiam_serviceimportaccelbyte_py_sdk.api.iam.modelsasiam_modelsfromaccelbyte_py_sdkimportAccelByteSDKfromaccelbyte_py_sdk.coreimportEnvironmentConfigRepositoryfromaccelbyte_py_sdk.coreimportInMemoryTokenRepository# Create 3 instances of the SDKclient_sdk=AccelByteSDK()user_sdk1=AccelByteSDK()user_sdk2=AccelByteSDK()# Initialize the SDKsclient_sdk.initialize(options={"config":EnvironmentConfigRepository(),"token":InMemoryTokenRepository(),})user_sdk1.initialize(options={"config":EnvironmentConfigRepository(),"token":InMemoryTokenRepository(),})user_sdk2.initialize(options={"config":user_sdk1.get_config_repository(),# you could also share the config repo with User 1 SDK's"token":InMemoryTokenRepository(),# you could also do the same thing with token repos but that is not advisable.})# Login the SDKs_,error=auth_service.login_client(sdk=client_sdk)username1,password1=..._,error=auth_service.login_user(username1,password1,sdk=user_sdk1)username2,password2=..._,error=auth_service.login_user(username2,password2,sdk=user_sdk2)# Call an endpoint as User 1result1,error=iam_service.public_create_user_v4(body=iam_models.AccountCreateUserRequestV4.create_from_dict({...}),sdk=user_sdk1,)# Call an endpoint as User 2result2,error=iam_service.public_create_user_v4(body=iam_models.AccountCreateUserRequestV4.create_from_dict({...}),sdk=user_sdk2,)# Call an endpoint as the Admin IAM Clientresult,error=admin_update_user_v4(body=iam_models.ModelUserUpdateRequestV3.create_from_dict({...}),user_id=result1.user_id,sdk=client_sdk,)# Reset/Deintialize the SDKs after usingclient_sdk1.deintialize()client_sdk1.deintialize()client_sdk1.deintialize()Interacting with a Service EndpointExample AIn this example we will create a new user using thePOSTendpoint/iam/v3/public/namespaces/{namespace}/usersimportjsonimportaccelbyte_py_sdkfromaccelbyte_py_sdk.services.authimportlogin_client# Import the wrapper 'public_create_user_v3'# to know which wrapper to use open the docs/<service-name>-index.md and# use the search function to find the wrapper namefromaccelbyte_py_sdk.api.iamimportpublic_create_user_v3# This POST endpoint also requires a body of 'ModelUserCreateRequestV3'# so you will need to import that too, import it using this scheme:#  from accelbyte_py_sdk.api.<service-name>.models import <model-name>fromaccelbyte_py_sdk.api.iam.modelsimportModelUserCreateRequestV3fromaccelbyte_py_sdk.api.iam.modelsimportModelUserCreateResponseV3defmain():# 1 Initialize the SDKaccelbyte_py_sdk.initialize()# 2 Login as a client (uses $AB_CLIENT_ID and $AB_CLIENT_SECRET)_,error=login_client()# 3 Create a user using the POST endpoint: /iam/v3/public/namespaces/{namespace}/users#   * this endpoint requires:#     - a 'body' (ModelUserCreateRequestV3)#     - a 'namespace' (string)#       'namespace' here is unique because it can be omitted, omitting it will result in#       the SDK to automatically fill it out with the value of '$AB_NAMESPACE'#   * more details on this endpoint can be found in:#     accelbyte_py_sdk/api/iam/operations/users/public_create_user_v3.pyresult,error=public_create_user_v3(body=ModelUserCreateRequestV3.create(auth_type="EMAILPASSWD",country="US",date_of_birth="2001-01-01",display_name="************",email_address="******@fakemail.com",password="******************",))# 4 Check for errorsiferror:exit(1)# 5 Do something with the resultprint(json.dumps(result.to_dict(),indent=2))# {#   "authType": "EMAILPASSWD",#   "country": "US",#   "dateOfBirth": "2001-01-01T00:00:00Z",#   "displayName": "************",#   "emailAddress": "******@fakemail.com",#   "namespace": "******",#   "userId": "********************************"# }if__name__=="__main__":main():bulb: All wrapper functions follow the return value format ofresult, error.:bulb: You could also write your own wrapper functions by using the models and operations inaccelbyte_py_sdk.api.<service-name>andaccelbyte_py_sdk.api.<service-name>.modelsrespectively.:bulb: All wrapper functions have an asynchronous counterpart that ends with_async.Example A (async)To convertExample Aasynchronously the following steps are needed.Import the asyncio package.importasyncioConvert the main method intoasync.# def main():asyncdefmain():Change how themainfunction is invoked.if__name__=="__main__":# main()loop=asyncio.get_event_loop()loop.run_until_complete(main())UseHttpxHttpClient.# accelbyte_py_sdk.initialize()accelbyte_py_sdk.initialize(options={"http":"HttpxHttpClient"})Use theasyncversion of the wrapper by appending_async.# from accelbyte_py_sdk.api.iam import public_create_user_v3fromaccelbyte_py_sdk.api.iamimportpublic_create_user_v3_asyncUse theasyncwrapper with theawaitkeyword.# result, error = public_create_user_v3(result,error=awaitpublic_create_user_v3_async(Here is the full code:importasyncioimportjsonimportaccelbyte_py_sdkfromaccelbyte_py_sdk.services.authimportlogin_client# Import the wrapper 'public_create_user_v3_async'# to know which wrapper to use open the docs/<service-name>-index.md and# use the search function to find the wrapper namefromaccelbyte_py_sdk.api.iamimportpublic_create_user_v3_async# This POST endpoint also requires a body of 'ModelUserCreateRequestV3'# so you will need to import that too, import it using this scheme:#  from accelbyte_py_sdk.api.<service-name>.models import <model-name>fromaccelbyte_py_sdk.api.iam.modelsimportModelUserCreateRequestV3fromaccelbyte_py_sdk.api.iam.modelsimportModelUserCreateResponseV3asyncdefmain():# 1 Initialize the SDKaccelbyte_py_sdk.initialize(options={"http":"HttpxHttpClient"})# 2 Login as a client (uses $AB_CLIENT_ID and $AB_CLIENT_SECRET)_,error=login_client()# 3 Create a user using the POST endpoint: /iam/v3/public/namespaces/{namespace}/users#   * this endpoint requires:#     - a 'body' (ModelUserCreateRequestV3)#     - a 'namespace' (string)#       'namespace' here is unique because it can be omitted, omitting it will result in#       the SDK to automatically fill it out with the value of '$AB_NAMESPACE'#   * more details on this endpoint can be found in:#     accelbyte_py_sdk/api/iam/operations/users/public_create_user_v3.pyresult,error=awaitpublic_create_user_v3_async(body=ModelUserCreateRequestV3.create(auth_type="EMAILPASSWD",country="US",date_of_birth="2001-01-01",display_name="************",email_address="******@fakemail.com",password="******************",))# 4 Check for errorsiferror:exit(1)# 5 Do something with the resultprint(json.dumps(result.to_dict(),indent=2))# {#   "authType": "EMAILPASSWD",#   "country": "US",#   "dateOfBirth": "2001-01-01T00:00:00Z",#   "displayName": "************",#   "emailAddress": "******@fakemail.com",#   "namespace": "******",#   "userId": "********************************"# }if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())Configuring HTTP RetryTo use theHTTP Retryfeature, set theHttpClient'sretry_policyandbackoff_policy.importaccelbyte_py_sdkfromaccelbyte_py_sdk.coreimportget_http_client# 1 Initialize the SDKaccelbyte_py_sdk.initialize()# 2 Get the HTTP Clienthttp_client=get_http_client()# 3 Configure the `retry_policy` and `backoff_policy`# 3a. Retry 3 times with 0.5 seconds delay in betweenfromaccelbyte_py_sdk.coreimportConstantHttpBackoffPolicyfromaccelbyte_py_sdk.coreimportMaxRetriesHttpRetryPolicyhttp_client.retry_policy=MaxRetriesHttpRetryPolicy(3)# 3b. Retry when total elapsed time is less than 15 seconds, with an exponential backoff duration.fromaccelbyte_py_sdk.coreimportExponentialHttpBackoffPolicyfromaccelbyte_py_sdk.coreimportMaxElapsedHttpRetryPolicyhttp_client.backoff_policy=ExponentialHttpBackoffPolicy(initial=1.0,multiplier=2.0)http_client.retry_policy=MaxElapsedHttpRetryPolicy(15)# 3c. Use custom retry and backoff policies.fromdatetimeimporttimedeltafromtypingimportOptionaldefmy_custom_retry_policy(request,response,/,*,retries:int=0,elapsed:Optional[timedelta]=None,**kwargs)->float:return"Retry-After"inresponse.headersandretries==1# Retry if the 'Retry-After' header exists and we are on the 1st retry (2nd attempt).defmy_custom_backoff_policy(request,response,/,*,retries:int=0,elapsed:Optional[timedelta]=None,**kwargs)->float:returnresponse.headers.get("Retry-After",1)# Use the value of the 'Retry-After' response header, default to 1.0s.http_client.backoff_policy=my_custom_backoff_policyhttp_client.retry_policy=my_custom_retry_policy# 3d. Combining multiple retry policies.fromaccelbyte_py_sdk.coreimportCompositeHttpRetryPolicyfromaccelbyte_py_sdk.coreimportMaxRetriesHttpRetryPolicyfromaccelbyte_py_sdk.coreimportStatusCodesHttpRetryPolicyhttp_client.retry_policy=CompositeHttpRetryPolicy(StatusCodesHttpRetryPolicy(401,(501,503)),# Retry when response status code is 401, 501 to 503 (501, 502, or 503) -- ANDMaxRetriesHttpRetryPolicy(3)#       when number of retries is less than or equal to 3.)Validating TokensYou can useaccelbyte_py_sdk.token_validation.caching.CachingTokenValidatororaccelbyte_py_sdk.token_validation.iam.IAMTokenValidator.token_validator=CachingTokenValidator(sdk)# or IAMTokenValidator(sdk)# access_token = ...error=token_validator.validate_token(access_token)iferror:raiseerrorParsing TokensYou can useparse_access_tokenfromaccelbyte_py_sdk.services.auth.fromaccelbyte_py_sdk.services.authimportparse_access_token# access_token = ...claims,error=parse_access_token(access_token)iferror:exit(1)You can also do validation in the same call. By default, it usesCachingTokenValidator.fromaccelbyte_py_sdk.services.authimportparse_access_token# access_token = ...claims,error=parse_access_token(access_token,validate=True)iferror:exit(1)You can specify what kind (or which) of validator you want to use.fromaccelbyte_py_sdk.services.authimportparse_access_token# access_token = ...claims,error=parse_access_token(access_token,validator="iam")# or validator="caching"iferror:exit(1)fromaccelbyte_py_sdk.services.authimportparse_access_tokentoken_validator=CachingTokenValidator(sdk)# or IAMTokenValidator(sdk)# access_token = ...claims,error=parse_access_token(access_token,validator=token_validator)iferror:exit(1)Seetestsfor more usage.SamplesSample apps are available in thesamplesdirectoryDocumentationFor documentation about AccelByte services and SDK, seedocs.accelbyte.io:bulb: Check out the index files in thedocsdirectory if you are looking for a specific endpoint.MiscUtility FunctionsCheck if the SDK is initialized.importaccelbyte_py_sdkis_initialized=accelbyte_py_sdk.is_initialized()print(is_initialized)# FalseCreate a Basic Auth from a string tuple.importaccelbyte_py_sdkbasic_auth=accelbyte_py_sdk.core.create_basic_authentication("foo","bar")print(basic_auth)# Basic Zm9vOmJhcg==Gets the stored access token.importaccelbyte_py_sdkaccess_token,error=accelbyte_py_sdk.core.get_access_token()print(access_token)# ************************************GetAB_*environment configuration values.importaccelbyte_py_sdkbase_url,client_id,client_secret,namespace=accelbyte_py_sdk.core.get_env_config()print(f"{base_url},{client_id},{client_secret},{namespace}")# <$AB_BASE_URL>, <$AB_CLIENT_ID>, <$AB_CLIENT_SECRET>, <$AB_NAMESPACE>GetAB_*environment user credential values.importaccelbyte_py_sdkusername,password=accelbyte_py_sdk.core.get_env_user_credentials()print(f"{base_url}:{client_id}")# <$AB_USERNAME>: <$AB_PASSWORD>Set logger level and add logger handlers.importlogging# 1. The SDK has helper functions for logging.accelbyte_py_sdk.core.set_logger_level(logging.INFO)# 'accelbyte_py_sdk'accelbyte_py_sdk.core.set_logger_level(logging.INFO,"http")# 'accelbyte_py_sdk.http'accelbyte_py_sdk.core.set_logger_level(logging.INFO,"ws")# 'accelbyte_py_sdk.ws'# 2. You could also use this helper function for debugging.accelbyte_py_sdk.core.add_stream_handler_to_logger()# sends content of the 'accelbyte_py_sdk' logger to 'sys.stderr'.# 3. There is a helper function that helps you get started with log files.accelbyte_py_sdk.core.add_buffered_file_handler_to_logger(# flushes content of the 'accelbyte_py_sdk' logger to a file named 'sdk.log' every 10 logs.filename="/path/to/sdk.log",capacity=10,level=logging.INFO)accelbyte_py_sdk.core.add_buffered_file_handler_to_logger(# flushes content of the 'accelbyte_py_sdk.http' logger to a file named 'http.log' every 3 logs.filename="/path/to/http.log",capacity=3,level=logging.INFO,additional_scope="http")# 3.a. Or you could the same thing when initializing the SDK.accelbyte_py_sdk.initialize(options={"log_files":{"":"/path/to/sdk.log",# flushes content of the 'accelbyte_py_sdk' logger to a file named 'sdk.log' every 10 logs."http":{# flushes content of the 'accelbyte_py_sdk.http' logger to a file named 'http.log' every 3 logs."filename":"/path/to/http.log","capacity":3,"level":logging.INFO}}})# 4. By default logs from 'accelbyte_py_sdk.http' are stringified dictionaries, you can set your own formatter like so.defformat_request_response_as_yaml(data:dict)->str:returnf"---\n{yaml.safe_dump(data,sort_keys=False).rstrip()}\n..."http_client=accelbyte_py_sdk.core.get_http_client()http_client.request_log_formatter=format_request_response_as_yamlhttp_client.response_log_formatter=format_request_response_as_yamlIn-depth TopicsGenerated codeModelsEach definition in#/definitions/is turned into a Model.Example:# UserProfileInfoproperties:avatarLargeUrl:type:stringavatarSmallUrl:type:stringavatarUrl:type:stringcustomAttributes:additionalProperties:type:objecttype:objectdateOfBirth:format:datetype:stringx-nullable:truefirstName:type:stringlanguage:type:stringlastName:type:stringnamespace:type:stringstatus:enum:-ACTIVE-INACTIVEtype:stringtimeZone:type:stringuserId:type:stringzipCode:type:stringtype:object# accelbyte_py_sdk/api/basic/models/user_profile_info.pyclassUserProfileInfo(Model):"""User profile info (UserProfileInfo)Properties:avatar_large_url: (avatarLargeUrl) OPTIONAL stravatar_small_url: (avatarSmallUrl) OPTIONAL stravatar_url: (avatarUrl) OPTIONAL strcustom_attributes: (customAttributes) OPTIONAL Dict[str, Any]date_of_birth: (dateOfBirth) OPTIONAL strfirst_name: (firstName) OPTIONAL strlanguage: (language) OPTIONAL strlast_name: (lastName) OPTIONAL strnamespace: (namespace) OPTIONAL strstatus: (status) OPTIONAL Union[str, StatusEnum]time_zone: (timeZone) OPTIONAL struser_id: (userId) OPTIONAL strzip_code: (zipCode) OPTIONAL str"""# region fieldsavatar_large_url:str# OPTIONALavatar_small_url:str# OPTIONALavatar_url:str# OPTIONALcustom_attributes:Dict[str,Any]# OPTIONALdate_of_birth:str# OPTIONALfirst_name:str# OPTIONALlanguage:str# OPTIONALlast_name:str# OPTIONALnamespace:str# OPTIONALstatus:Union[str,StatusEnum]# OPTIONALtime_zone:str# OPTIONALuser_id:str# OPTIONALzip_code:str# OPTIONAL# endregion fieldsthere are also a number of utility functions generated with each model that should help in the ease of use.# accelbyte_py_sdk/api/basic/models/user_profile_info.py...defwith_user_id(self,value:str)->UserProfileInfo:self.user_id=valuereturnself# other with_x() methods toodefto_dict(self,include_empty:bool=False)->dict:result:dict={}...returnresult@classmethoddefcreate(cls,avatar_large_url:Optional[str]=None,avatar_small_url:Optional[str]=None,avatar_url:Optional[str]=None,custom_attributes:Optional[Dict[str,Any]]=None,date_of_birth:Optional[str]=None,first_name:Optional[str]=None,language:Optional[str]=None,last_name:Optional[str]=None,namespace:Optional[str]=None,status:Optional[Union[str,StatusEnum]]=None,time_zone:Optional[str]=None,user_id:Optional[str]=None,zip_code:Optional[str]=None,)->UserProfileInfo:instance=cls()...returninstance@classmethoddefcreate_from_dict(cls,dict_:dict,include_empty:bool=False)->UserProfileInfo:instance=cls()...returninstance@staticmethoddefget_field_info()->Dict[str,str]:return{"avatarLargeUrl":"avatar_large_url","avatarSmallUrl":"avatar_small_url","avatarUrl":"avatar_url","customAttributes":"custom_attributes","dateOfBirth":"date_of_birth","firstName":"first_name","language":"language","lastName":"last_name","namespace":"namespace","status":"status","timeZone":"time_zone","userId":"user_id","zipCode":"zip_code",}...OperationsEach path item in#/pathsis turned into an Operation.Example:# GET /basic/v1/public/namespaces/{namespace}/users/{userId}/profilesdescription:'Getuserprofile.&lt;br&gt;Otherdetailinfo:&lt;ul&gt;&lt;li&gt;&lt;i&gt;Requiredpermission&lt;/i&gt;:resource=&lt;b&gt;&#34;NAMESPACE:{namespace}:USER:{userId}:PROFILE&#34;&lt;/b&gt;,action=2&lt;b&gt;(READ)&lt;/b&gt;&lt;/li&gt;&lt;li&gt;&lt;i&gt;Actioncode&lt;/i&gt;:11403&lt;/li&gt;&lt;li&gt;&lt;i&gt;Returns&lt;/i&gt;:userprofile&lt;/li&gt;&lt;/ul&gt;'operationId:publicGetUserProfileInfoparameters:-description:namespace, only accept alphabet and numericin:pathname:namespacerequired:truetype:string-description:user's id, should follow UUID version 4 without hyphenin:pathname:userIdrequired:truetype:stringproduces:-application/jsonresponses:'200':description:Successful operationschema:$ref:'#/definitions/UserProfileInfo''400':description:<table><tr><td>errorCode</td><td>errorMessage</td></tr><tr><td>20002</td><td>validationerror</td></tr></table>schema:$ref:'#/definitions/ValidationErrorEntity''401':description:<table><tr><td>errorCode</td><td>errorMessage</td></tr><tr><td>20001</td><td>unauthorized</td></tr></table>schema:$ref:'#/definitions/ErrorEntity''403':description:<table><tr><td>errorCode</td><td>errorMessage</td></tr><tr><td>20013</td><td>insufficientpermission</td></tr></table>schema:$ref:'#/definitions/ErrorEntity''404':description:'<table><tr><td>errorCode</td><td>errorMessage</td></tr><tr><td>11440</td><td>Unableto{action}:Userprofilenotfoundinnamespace[{namespace}]</td></tr></table>'schema:$ref:'#/definitions/ErrorEntity'security:-authorization:[]-HasPermission:-NAMESPACE:{namespace}:USER:{userId}:PROFILE [READ]authorization:[]summary:Get user profiletags:-UserProfilex-authorization:action:'2'resource:NAMESPACE:{namespace}:USER:{userId}:PROFILEsame with the models there are also a number of utility functions generated with each operation that should help in the ease of use.# accelbyte_py_sdk/api/basic/operations/user_profile/get_user_profile_info.py# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.# This is licensed software from AccelByte Inc, for limitations# and restrictions contact your company contract manager.## Code generated. DO NOT EDIT!# template file: accelbyte_gaming services_py_codegen# pylint: disable=duplicate-code# pylint: disable=line-too-long# pylint: disable=missing-function-docstring# pylint: disable=missing-module-docstring# pylint: disable=too-many-arguments# pylint: disable=too-many-branches# pylint: disable=too-many-instance-attributes# pylint: disable=too-many-lines# pylint: disable=too-many-locals# pylint: disable=too-many-public-methods# pylint: disable=too-many-return-statements# pylint: disable=too-many-statements# pylint: disable=unused-import# AccelByte Gaming Services Basic Service (1.36.1)from__future__importannotationsfromtypingimportAny,Dict,List,Optional,Tuple,Unionfrom.....coreimportOperationfrom.....coreimportHeaderStrfrom.....coreimportHttpResponsefrom...modelsimportErrorEntityfrom...modelsimportUserProfilePrivateInfofrom...modelsimportValidationErrorEntityclassGetUserProfileInfo(Operation):"""Get user profile (getUserProfileInfo)Get user profile.Other detail info:* Required permission : resource= "ADMIN:NAMESPACE:{namespace}:USER:{userId}:PROFILE" , action=2 (READ)*  Returns : user profile*  Action code : 11403Required Permission(s):- ADMIN:NAMESPACE:{namespace}:USER:{userId}:PROFILE [READ]Properties:url: /basic/v1/admin/namespaces/{namespace}/users/{userId}/profilesmethod: GETtags: ["UserProfile"]consumes: []produces: ["application/json"]securities: [BEARER_AUTH] or [BEARER_AUTH]namespace: (namespace) REQUIRED str in pathuser_id: (userId) REQUIRED str in pathResponses:200: OK - UserProfilePrivateInfo (successful operation)400: Bad Request - ValidationErrorEntity (20002: validation error)401: Unauthorized - ErrorEntity (20001: unauthorized)403: Forbidden - ErrorEntity (20013: insufficient permission)404: Not Found - ErrorEntity (11440: Unable to {action}: User profile not found in namespace [{namespace}])"""# region fields_url:str="/basic/v1/admin/namespaces/{namespace}/users/{userId}/profiles"_method:str="GET"_consumes:List[str]=[]_produces:List[str]=["application/json"]_securities:List[List[str]]=[["BEARER_AUTH"],["BEARER_AUTH"]]_location_query:str=Nonenamespace:str# REQUIRED in [path]user_id:str# REQUIRED in [path]# endregion fields# region properties@propertydefurl(self)->str:returnself._url@propertydefmethod(self)->str:returnself._method@propertydefconsumes(self)->List[str]:returnself._consumes@propertydefproduces(self)->List[str]:returnself._produces@propertydefsecurities(self)->List[List[str]]:returnself._securities@propertydeflocation_query(self)->str:returnself._location_query# endregion properties# region get methods# endregion get methods# region get_x_params methodsdefget_all_params(self)->dict:return{"path":self.get_path_params(),}defget_path_params(self)->dict:result={}ifhasattr(self,"namespace"):result["namespace"]=self.namespaceifhasattr(self,"user_id"):result["userId"]=self.user_idreturnresult# endregion get_x_params methods# region is/has methods# endregion is/has methods# region with_x methodsdefwith_namespace(self,value:str)->GetUserProfileInfo:self.namespace=valuereturnselfdefwith_user_id(self,value:str)->GetUserProfileInfo:self.user_id=valuereturnself# endregion with_x methods# region to methodsdefto_dict(self,include_empty:bool=False)->dict:result:dict={}ifhasattr(self,"namespace")andself.namespace:result["namespace"]=str(self.namespace)elifinclude_empty:result["namespace"]=""ifhasattr(self,"user_id")andself.user_id:result["userId"]=str(self.user_id)elifinclude_empty:result["userId"]=""returnresult# endregion to methods# region response methods# noinspection PyMethodMayBeStaticdefparse_response(self,code:int,content_type:str,content:Any)->Tuple[Union[None,UserProfilePrivateInfo],Union[None,ErrorEntity,HttpResponse,ValidationErrorEntity]]:"""Parse the given response.200: OK - UserProfilePrivateInfo (successful operation)400: Bad Request - ValidationErrorEntity (20002: validation error)401: Unauthorized - ErrorEntity (20001: unauthorized)403: Forbidden - ErrorEntity (20013: insufficient permission)404: Not Found - ErrorEntity (11440: Unable to {action}: User profile not found in namespace [{namespace}])---: HttpResponse (Undocumented Response)---: HttpResponse (Unexpected Content-Type Error)---: HttpResponse (Unhandled Error)"""pre_processed_response,error=self.pre_process_response(code=code,content_type=content_type,content=content)iferrorisnotNone:returnNone,Noneiferror.is_no_content()elseerrorcode,content_type,content=pre_processed_responseifcode==200:returnUserProfilePrivateInfo.create_from_dict(content),Noneifcode==400:returnNone,ValidationErrorEntity.create_from_dict(content)ifcode==401:returnNone,ErrorEntity.create_from_dict(content)ifcode==403:returnNone,ErrorEntity.create_from_dict(content)ifcode==404:returnNone,ErrorEntity.create_from_dict(content)returnself.handle_undocumented_response(code=code,content_type=content_type,content=content)# endregion response methods# region static methods@classmethoddefcreate(cls,namespace:str,user_id:str,)->GetUserProfileInfo:instance=cls()instance.namespace=namespaceinstance.user_id=user_idreturninstance@classmethoddefcreate_from_dict(cls,dict_:dict,include_empty:bool=False)->GetUserProfileInfo:instance=cls()if"namespace"indict_anddict_["namespace"]isnotNone:instance.namespace=str(dict_["namespace"])elifinclude_empty:instance.namespace=""if"userId"indict_anddict_["userId"]isnotNone:instance.user_id=str(dict_["userId"])elifinclude_empty:instance.user_id=""returninstance@staticmethoddefget_field_info()->Dict[str,str]:return{"namespace":"namespace","userId":"user_id",}@staticmethoddefget_required_map()->Dict[str,bool]:return{"namespace":True,"userId":True,}# endregion static methodsCreating:bulb: there are 4 ways to create an instance of these models and operations.# 1. using the python __init__() function then setting the parameters manually:model=ModelName()model.param_a="foo"model.param_b="bar"# 2. using the python __init__() function together with the 'with_x' methods:# # the 'with_x' functions are type annotated and will show warnings if a wrong type is passed.model=ModelName()\.with_param_a("foo")\.with_param_b("bar")# 3. using the ModelName.create(..) class method:# # parameters here are also type annotated and will throw a TypeError if a required field was not filled out.model=ModelName.create(param_a="foo",param_b="bar",)# 4. using the ModelName.create_from_dict(..) class method:# # this method also has a 'include_empty' option that would get ignore values that evaluate to False, None, or len() == 0.model_params={"param_a":"foo","param_b":"bar","param_c":False,"param_d":None,"param_e":[],"param_f":{},}model=ModelName.create_from_dict(model_params)# all of these apply to all operations too.WrappersTo improve ergonomics the code generator also generates wrappers around the operations.
The purpose of these wrappers is to automatically fill up parameters that the SDK already knows.
(e.g. namespace, client_id, access_token, etc.)They are located ataccelbyte_py_sdk.api.<service-name>.wrappersbut can be accessed like so:from accelbyte_py_sdk.api.<service-name> import <wrapper-name>importaccelbyte_py_sdkfromaccelbyte_py_sdk.api.iamimporttoken_grant_v3if__name__=="__main__":accelbyte_py_sdk.initialize()token,error=token_grant_v3(grant_type="client_credentials")asserterrorisnotNoneThe wrapper functiontoken_grant_v3is a wrapper for theTokenGrantV3operation.
It automatically passes in the information needed like the Basic Auth Headers.
The values are gotten from the currentConfigRepository.continuing from the previous examples (GetUserProfileInfo), its wrapper would be:# accelbyte_py_sdk/api/basic/wrappers/_user_profile.pyfromtypingimportAny,Dict,List,Optional,Tuple,Unionfrom....coreimportget_namespaceasget_services_namespacefrom....coreimportrun_requestfrom....coreimportsame_doc_asfrom..operations.user_profileimportGetUserProfileInfo@same_doc_as(GetUserProfileInfo)defget_user_profile_info(user_id:str,namespace:Optional[str]=None):ifnamespaceisNone:namespace,error=get_services_namespace()iferror:returnNone,errorrequest=GetUserProfileInfo.create(user_id=user_id,namespace=namespace,)returnrun_request(request)this wrapper function automatically fills up the required path parameternamespace.now to use it only theuser_idis now required.importaccelbyte_py_sdkfromaccelbyte_py_sdk.api.basicimportget_user_profile_infoif__name__=="__main__":accelbyte_py_sdk.initialize()user_profile_info,error=get_user_profile_info(user_id="lorem")asserterrorisnotNoneprint(f"Hello there{user_profile_info.first_name}!")