Package: xbox-webapi
Xbox-WebAPIXbox-WebAPI is a python library to authenticate with Xbox Live via your Microsoft Account and provides Xbox related Web-API.Authentication is supported via OAuth2.Register a new application inAzure ADName your appSelect "Personal Microsoft accounts only" under supported account typesAddhttp://localhost/auth/callbackas a Redirect URI of type "Web"Copy your Application (client) ID for later useOn the App Page, navigate to "Certificates & secrets"Generate a new client secret and save for later useDependenciesPython >= 3.8How to useInstallpip install xbox-webapiAuthenticationNote: You must use non child account (> 18 years old)Token save location: If tokenfile is not provided via cmdline, fallback of<appdirs.user_data_dir>/tokens.jsonis used as save-locationSpecifically:Windows:C:\\Users\\<username>\\AppData\\Local\\OpenXbox\\xboxMac OSX:/Users/<username>/Library/Application Support/xbox/tokens.jsonLinux:/home/<username>/.local/share/xboxFor more information, see:https://pypi.org/project/appdirsand module:xbox.webapi.scripts.constantsxbox-authenticate --client-id <client-id> --client-secret <client-secret>Example: Search Xbox Live via cmdline tool# Search Xbox One Catalog
  xbox-searchlive "Some game title"API usageimportasyncioimportsysfromhttpximportHTTPStatusErrorfromxbox.webapi.api.clientimportXboxLiveClientfromxbox.webapi.authentication.managerimportAuthenticationManagerfromxbox.webapi.authentication.modelsimportOAuth2TokenResponsefromxbox.webapi.common.signed_sessionimportSignedSessionfromxbox.webapi.scriptsimportCLIENT_ID,CLIENT_SECRET,TOKENS_FILE"""This uses the global default client identification by OpenXboxYou can supply your own parameters here if you are permitted to createnew Microsoft OAuth Apps and know what you are doing"""client_id=CLIENT_IDclient_secret=CLIENT_SECRETtokens_file=TOKENS_FILE"""For doing authentication, see xbox/webapi/scripts/authenticate.py"""asyncdefasync_main():# Create a HTTP client sessionasyncwithSignedSession()assession:"""Initialize with global OAUTH parameters from above"""auth_mgr=AuthenticationManager(session,client_id,client_secret,"")"""Read in tokens that you received from the `xbox-authenticate`-script previouslySee `xbox/webapi/scripts/authenticate.py`"""try:withopen(tokens_file)asf:tokens=f.read()# Assign gathered tokensauth_mgr.oauth=OAuth2TokenResponse.model_validate_json(tokens)exceptFileNotFoundErrorase:print(f"File{tokens_file}isn`t found or it doesn`t contain tokens! err={e}")print("Authorizing via OAUTH")url=auth_mgr.generate_authorization_url()print(f"Auth via URL:{url}")authorization_code=input("Enter authorization code> ")tokens=awaitauth_mgr.request_oauth_token(authorization_code)auth_mgr.oauth=tokens"""Refresh tokens, just in caseYou could also manually check the token lifetimes and just refresh themif they are close to expiry"""try:awaitauth_mgr.refresh_tokens()exceptHTTPStatusErrorase:print(f"""Could not refresh tokens from{tokens_file}, err={e}\nYou might have to delete the tokens file and re-authenticateif refresh token is expired""")sys.exit(-1)# Save the refreshed/updated tokenswithopen(tokens_file,mode="w")asf:f.write(auth_mgr.oauth.json())print(f"Refreshed tokens in{tokens_file}!")"""Construct the Xbox API client from AuthenticationManager instance"""xbl_client=XboxLiveClient(auth_mgr)"""Some example API calls"""# Get friendslistfriendslist=awaitxbl_client.people.get_friends_own()print(f"Your friends:{friendslist}\n")# Get presence status (by list of XUID)presence=awaitxbl_client.presence.get_presence_batch(["2533274794093122","2533274807551369"])print(f"Statuses of some random players by XUID:{presence}\n")# Get messagesmessages=awaitxbl_client.message.get_inbox()print(f"Your messages:{messages}\n")# Get profile by GTprofile=awaitxbl_client.profile.get_profile_by_gamertag("SomeGamertag")print(f"Profile under SomeGamertag gamer tag:{profile}\n")asyncio.run(async_main())ContributeReport bugs/suggest featuresAdd/update docsAdd additional xbox live endpointsCreditsThis package uses parts ofCookiecutterand theaudreyr/cookiecutter-pypackageproject template.
The authentication code is based onjoealcorn/xboxInformations on endpoints gathered from:XboxLive REST ReferenceXboxLiveTraceAnalyzer APIMapXbox Live Service APIDisclaimerXbox, Xbox One, Smartglass and Xbox Live are trademarks of Microsoft Corporation. Team OpenXbox is in no way endorsed by or affiliated with Microsoft Corporation, or any associated subsidiaries, logos or trademarks.