> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How to use XBOX services APIs

> Initialize GRTS, create an XTaskQueue, set up HttpClient tracing, and call XblInitialize to start using the XBOX services API (XSAPI) C functions in your title.

This topic shows how to set up the XBOX services API (XSAPI) in your game, create an XBOX services context for a signed-in user, and make your first call to XBOX services.

## Before you begin

Complete these steps before you write code:

* Create your product in Partner Center, enable XBOX services, and publish the service configuration to your development sandbox. For more information, see [Setting up an app or game at Partner Center, for Managed Partners](https://docs.xbox.com/services/xbox-services/fundamentals/portal-config/live-setup-partner-center-partners.md).
* Set the `TitleId` and `MSAAppId` elements in your `MicrosoftGame.config` file. The values must exactly match the **Title ID (hexadecimal)** and **MSA App ID** values in Partner Center.
* Copy the Service Configuration ID (SCID) from the **Identity details** section of the **Game setup** page in Partner Center. You pass the SCID to `XblInitialize`. The SCID is case-sensitive.
* Set your dev kit or Windows PC to your development sandbox, and sign in with a test account that has access to that sandbox. For more information, see [Setting up sandboxes](https://docs.xbox.com/services/xbox-services/fundamentals/sandboxes/live-setting-up-sandboxes.md) and [Troubleshooting Sign-in and Sandbox Errors](https://docs.xbox.com/services/xbox-services/develop/troubleshooting/live-troubleshoot-sandboxes.md).
* Include `xsapi-c/services_c.h`. To link XSAPI statically, link `Microsoft.Xbox.Services.143.C.lib` (or `Microsoft.Xbox.Services.142.C.lib` with the v142 toolset; ARM64 provides only the 143 library), together with `libHttpClient.lib`, the import library for `libHttpClient.dll`. To use the XSAPI DLL, link `Microsoft.Xbox.Services.C.Thunks.lib`. If more than one DLL in your game calls XSAPI, use the DLL so that all of them share one XSAPI instance. Copy `libHttpClient.dll`, and `Microsoft.Xbox.Services.C.Thunks.dll` if you use the DLL, from the GDK `bin` folder into your game's layout. For the full list of libraries, see [GDK directory structure](https://docs.xbox.com/build/gdk-and-engines/guides/gdk-directory-structure.md).

## Initialize Gaming Runtime Services

XSAPIs depend on Gaming Runtime Services (GRTS). Before calling any XSAPIs, initialize GRTS, shown as follows.

```cpp theme={null}
#include <XGameRuntimeInit.h>
...
HRESULT hr = XGameRuntimeInitialize();
```

## Create XTaskQueue (optional)

Most of the XSAPIs are asynchronous APIs and require the use of a task queue. It's an API for queuing work and for completion task callbacks. To learn more about `XTaskQueue` and different dispatch modes, see [Async task queue design](https://docs.xbox.com/build/core-features/common/async/async-task-queue-design.md).

For example, the following code creates a task queue by using a system thread pool.

```cpp theme={null}
#include <XTaskQueue.h>
...
XTaskQueueHandle queue = nullptr;

HRESULT hr = XTaskQueueCreate(
    XTaskQueueDispatchMode::ThreadPool,
    XTaskQueueDispatchMode::ThreadPool,
    &queue);
```

Ensure that you release your acquired task queue handle back to the system when it's no longer needed.

```cpp theme={null}
XTaskQueueCloseHandle(queue);
queue = nullptr;
```

If you choose not to create your own task queue, ensure that you pass in `nullptr` when a queue handle is needed. When `nullptr` is used, the task system uses `ThreadPool` by default. It can be overridden by calling [XTaskQueueSetCurrentProcessTaskQueue](https://docs.xbox.com/reference/system/xtaskqueue/functions/xtaskqueuesetcurrentprocesstaskqueue.md).

## Set up HttpClient trace (optional)

To view additional runtime debug information, ensure that you set up the trace functionality of `HttpClient`.

The following code sets the `HttpClient` trace level and enables output for debugger information.

```cpp theme={null}
HCSettingsSetTraceLevel(HCTraceLevel::Verbose);
HCTraceSetTraceToDebugger(true);
```

## Initialize XSAPI

*Initialize XSAPI* before calling any XSAPIs.

```cpp theme={null}
#include <xsapi-c/services_c.h>
...
XblInitArgs xblArgs = {};
xblArgs.queue = queue; // Include this line only if you created your own XTaskQueue.
xblArgs.scid = "00000000-0000-0000-0000-000000000000"; // Replace with your SCID from Partner Center.

HRESULT hr = XblInitialize(&xblArgs);
if (FAILED(hr))
{
    // Handle the failure. Don't call other XSAPI functions until XblInitialize succeeds.
}
```

## Sign the user in to the XBOX network

Most of the XSAPIs require the user to first sign in to the XBOX network.
To sign a user in to the XBOX network, see the code example of the [XUserAddAsync API](https://docs.xbox.com/build/core-features/common/user/xuser_howto_best_practice_signing_in.md).

## Create an XBOX services context

An XBOX services context represents the service context that's associated with a particular user.

Most XSAPIs require you to pass in an `XblContextHandle` that represents the context of the calling user.
To create an XBOX services context, call [XblContextCreateHandle](https://docs.xbox.com/reference/live/xsapi-c/xbox_live_context_c/functions/xblcontextcreatehandle.md) and pass in the `XUserHandle` that you got from the previous step.

```cpp theme={null}
XblContextHandle xboxLiveContext = nullptr;
HRESULT hr = XblContextCreateHandle(userHandle, &xboxLiveContext);
if (FAILED(hr))
{
    // E_XBL_NOT_INITIALIZED: Call XblInitialize first.
    // E_INVALIDARG: userHandle or the output pointer is null.
}
```

Create one context for each signed-in user. If more than one component needs the same context, call [XblContextDuplicateHandle](https://docs.xbox.com/reference/live/xsapi-c/xbox_live_context_c/functions/xblcontextduplicatehandle.md) instead of creating a second context for the same user. Close every context handle with [XblContextCloseHandle](https://docs.xbox.com/reference/live/xsapi-c/xbox_live_context_c/functions/xblcontextclosehandle.md) when the user signs out or when you no longer need it.

## Make a service call to XBOX services

Now that you have an `XblContextHandle` for the user who signed in, you can make service calls to XBOX services.

For example, to retrieve the user's friends list, you can do the following:

```cpp theme={null}
#include <memory>
#include <xsapi-c/services_c.h>
...
auto asyncBlock = std::make_unique<XAsyncBlock>(); 
asyncBlock->queue = queue; // Or nullptr to use the process default task queue.
asyncBlock->callback = [](XAsyncBlock* asyncBlock)
{
    std::unique_ptr<XAsyncBlock> asyncBlockPtr{ asyncBlock }; // Take over ownership of the XAsyncBlock*.

    XblSocialRelationshipResultHandle relationshipResult{ nullptr };
    HRESULT hr = XblSocialGetSocialRelationshipsResult(asyncBlock, &relationshipResult);
    if (SUCCEEDED(hr))
    {
        // Use the result in the game.

        XblSocialRelationshipResultCloseHandle(relationshipResult);
    }
    else
    {
        // Handle the failure.
    }
};

HRESULT hr = XblSocialGetSocialRelationshipsAsync(
    xboxLiveContext,
    xboxUserId,
    socialRelationshipFilter,
    0,
    0,
    asyncBlock.get()
);

if (SUCCEEDED(hr))
{
    // The call succeeded. Release the std::unique_ptr ownership of XAsyncBlock* because the callback will take over ownership.
    // If the call fails, the std::unique_ptr will keep ownership and delete the XAsyncBlock*.
    asyncBlock.release();
}
else
{
    // Handle the failure.
}
// End of code example.
```

## Set the user's Rich Presence

To show what the player is doing in the game, set the user's Rich Presence when the player's activity changes, such as moving from the main menu into a match. For more information, see [Updating a user's Presence via XSAPI C](https://docs.xbox.com/services/xbox-services/community/presence/how-to/live-updating-user-presence.md).

## Clean up XSAPI

You don't need to call `XblCleanupAsync` when your game exits or is suspended. The operating system reclaims resources when the process exits, and XSAPI handles releasing and restoring the system resources that it needs across suspend and resume.

Call [XblCleanupAsync](https://docs.xbox.com/reference/live/xsapi-c/xbox_live_global_c/functions/xblcleanupasync.md) in these cases:

* You installed custom allocators with `XblMemSetFunctions`. Call `XblCleanupAsync`, and wait for it to finish, before you shut down your memory manager.
* You want to release XSAPI resources while the game keeps running, for example before you call `XblInitialize` again.

Before you call `XblCleanupAsync`, wait for your outstanding XSAPI calls to finish, and close your `XblContextHandle` handles with `XblContextCloseHandle`.


## Related topics

- [How to use the XBOX PC Remote Tools](https://docs.xbox.com/tools/tools-pc/xbox-pc-remote-tools/how-to-use-tools.md)
- [Client-side use of XBOX services user privileges](https://docs.xbox.com/services/xbox-services/fundamentals/identity/privileges/concepts/live-user-privileges-client.md)
- [How to](https://docs.xbox.com/services/xbox-services/multiplayer/invites/how-to/index.md)
