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

# Quickstart

> A quick introduction to building with Dari Link.

## Introduction

You'll need API keys, which you get by registering your app in the [console](https://console.dari.dev) under **Apps**. Choose the app type **Server**, and add the redirect URI `https://myapp.com/dari/callback`.

| You Need | In The Examples | What It Is |
| - | - | - |
| `client_id` | `CLIENT_ID` | Public identifier for your app. |
| `client_secret` | `CLIENT_SECRET` | Private key for your server. Shown once. |
| Environment | `DARI_GATEWAY_URL` | `https://routing.dari.dev` for hosted Dari, or the URL of [your own gateway](https://docs.dari.dev/link/run-a-gateway.md). |

To try the flow without a real subscription, point the examples at the [stub gateway](https://docs.dari.dev/link/test-your-integration.md).

> [accordion] Register with the API instead
>
> With an organization's API key, or on your own gateway. See [Register App](https://docs.dari.dev/link/reference/http.md#register-app).
>
> ```bash cURL theme={null}
> curl -X POST $DARI_GATEWAY_URL/v1/link/register \
>   -H "authorization: Bearer $DARI_API_KEY" \
>   -H "content-type: application/json" \
>   -d '{
>     "client_name": "My App",
>     "redirect_uris": ["https://myapp.com/dari/callback"],
>     "token_endpoint_auth_method": "client_secret_basic"
>   }'
> ```

## How It Works

Your app uses both a client-side component and a server to connect a user. The flow looks like this:

**The Link flow** begins when your user wants to connect their AI subscription to your app.

**Step 1**

Call [`DariLink.open`](https://docs.dari.dev/link/web#open) to open Link for your user. When they allow your app, Link provides a temporary `code`.

**Step 2**

Call [`/v1/link/token`](https://docs.dari.dev/link/reference/http#exchange-code) to exchange the `code` for a permanent `refresh_token` and `grant_id` for the new connection.

**Step 3**

Store the `refresh_token`. It is the only thing your app keeps for the connection.

**Step 4**

Use the `refresh_token` to make model requests on what your user connected.

The first step is to open Link. Link is a drop-in client-side module that handles the whole connection: signing in, picking plans and keys, and consent. It runs in the browser, so it is JavaScript whatever your server is written in. Once your user allows your app, `DariLink.open` resolves with a `code` and its `codeVerifier`, which your page sends to your server.

```js JavaScript theme={null}
import { DariLink } from "@mupt-ai/dari-gateway/link/client";

DariLink.renderButton(document.getElementById("connect-dari"), {
  onClick: async () => {
    const { code, codeVerifier } = await DariLink.open({
      gatewayUrl: DARI_GATEWAY_URL,
      clientId: "lnk_…",
      redirectUri: "https://myapp.com/dari/callback",
    });
    await fetch("/api/dari/connect", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ code, codeVerifier }),
    });
  },
});
```

```tsx React theme={null}
import { DariLink } from "@mupt-ai/dari-gateway/link/client";

export function ConnectWithDari() {
  const connect = async () => {
    const { code, codeVerifier } = await DariLink.open({
      gatewayUrl: DARI_GATEWAY_URL,
      clientId: "lnk_…",
      redirectUri: "https://myapp.com/dari/callback",
    });
    await fetch("/api/dari/connect", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ code, codeVerifier }),
    });
  };
  return <button onClick={connect}>Connect with Dari</button>;
}
```

```html HTML theme={null}
<div id="connect-dari"></div>

<script type="module">
  import { DariLink } from "https://cdn.jsdelivr.net/npm/@mupt-ai/dari-gateway@1/dist/link/client.js";

  DariLink.renderButton(document.getElementById("connect-dari"), {
    onClick: async () => {
      const { code, codeVerifier } = await DariLink.open({
        gatewayUrl: "https://routing.dari.dev",
        clientId: "lnk_…",
        redirectUri: "https://myapp.com/dari/callback",
      });
      await fetch("/api/dari/connect", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ code, codeVerifier }),
      });
    },
  });
</script>
```

The JavaScript and React tabs use the client from npm (`npm install @mupt-ai/dari-gateway`). The HTML tab needs nothing installed.

The page at your redirect URI runs one line, `DariLink.callback()`. See [callback()](https://docs.dari.dev/link/web.md#callback).

Next, on your server, call `/v1/link/token` to exchange the `code` for a `refresh_token`. The `refresh_token` uniquely identifies the connection and is a required argument for every later call. It never changes, and it is useless without your `client_secret`. Store it with your user in your own database.

```ts Node theme={null}
import { exchange } from "@mupt-ai/dari-gateway/link/client";

app.post("/api/dari/connect", async (req, res) => {
  const { refreshToken } = await exchange({
    gatewayUrl: DARI_GATEWAY_URL,
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
    redirectUri: "https://myapp.com/dari/callback",
    code: req.body.code,
    codeVerifier: req.body.codeVerifier,
  });
  // Save refreshToken to your database, with the signed-in user.
  res.end();
});
```

```python Python theme={null}
import requests

@app.post("/api/dari/connect")
def connect():
    body = request.get_json()
    reply = requests.post(f"{DARI_GATEWAY_URL}/v1/link/token",
        auth=(CLIENT_ID, CLIENT_SECRET),
        data={
            "grant_type": "authorization_code",
            "code": body["code"],
            "code_verifier": body["codeVerifier"],
            "redirect_uri": "https://myapp.com/dari/callback",
        })
    reply.raise_for_status()
    refresh_token = reply.json()["refresh_token"]
    # Save refresh_token to your database, with the signed-in user.
    return "", 204
```

```go Go theme={null}
func connect(w http.ResponseWriter, r *http.Request) {
	var body struct{ Code, CodeVerifier string }
	json.NewDecoder(r.Body).Decode(&body)

	form := url.Values{
		"grant_type":    {"authorization_code"},
		"code":          {body.Code},
		"code_verifier": {body.CodeVerifier},
		"redirect_uri":  {"https://myapp.com/dari/callback"},
	}
	req, _ := http.NewRequest("POST", dariGatewayURL+"/v1/link/token",
		strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.SetBasicAuth(clientID, clientSecret)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		http.Error(w, "Dari refused the code", http.StatusBadGateway)
		return
	}

	var tokens struct {
		RefreshToken string `json:"refresh_token"`
	}
	json.NewDecoder(res.Body).Decode(&tokens)
	// Save tokens.RefreshToken to your database, with the signed-in user.
}
```

```bash cURL theme={null}
curl -X POST $DARI_GATEWAY_URL/v1/link/token -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=authorization_code -d code=$CODE -d code_verifier=$CODE_VERIFIER \
  -d redirect_uri=https://myapp.com/dari/callback
# Store refresh_token from the reply.
```

Protect this endpoint from cross-site requests the way you protect any other that changes a user's account.

### Making API Requests

Now that your app has a `refresh_token`, it can make model requests on what the user connected. Dari's endpoints speak the OpenAI and Anthropic protocols, so any client for those works. A request carries an access token, which one call makes from the `refresh_token`. It lasts an hour: the Node client makes and keeps it for you, and in other languages you keep it and reuse it until it expires.

```ts Node theme={null}
import { linkFetch } from "@mupt-ai/dari-gateway/link/client";

// refreshToken: the one you saved for this user.
const dari = linkFetch({
  gatewayUrl: DARI_GATEWAY_URL,
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
  refreshToken,
});

const response = await dari("/v1/chat/completions", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ model: "dari/routing", messages: [{ role: "user", content: "Hi" }] }),
});
```

```python Python theme={null}
import requests

# 1. Get an access token from the refresh token you saved. It lasts an hour.
reply = requests.post(f"{DARI_GATEWAY_URL}/v1/link/token",
    auth=(CLIENT_ID, CLIENT_SECRET),
    data={"grant_type": "refresh_token", "refresh_token": refresh_token})
reply.raise_for_status()
access_token = reply.json()["access_token"]

# 2. Make the request.
response = requests.post(f"{DARI_GATEWAY_URL}/v1/chat/completions",
    headers={"Authorization": f"Bearer {access_token}"},
    json={"model": "dari/routing", "messages": [{"role": "user", "content": "Hi"}]})
```

```go Go theme={null}
// 1. Get an access token from the refresh token. It lasts an hour.
form := url.Values{
	"grant_type":    {"refresh_token"},
	"refresh_token": {refreshToken},
}
req, _ := http.NewRequest("POST", dariGatewayURL+"/v1/link/token",
	strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(clientID, clientSecret)
res, err := http.DefaultClient.Do(req)
if err != nil {
	return err
}
defer res.Body.Close()
var tokens struct {
	AccessToken string `json:"access_token"`
}
json.NewDecoder(res.Body).Decode(&tokens)

// 2. Make the request.
body := `{"model": "dari/routing", "messages": [{"role": "user", "content": "Hi"}]}`
req, _ = http.NewRequest("POST", dariGatewayURL+"/v1/chat/completions",
	strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
req.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(req)
```

```bash cURL theme={null}
# 1. Get an access token from the refresh token you saved. It lasts an hour.
curl -X POST $DARI_GATEWAY_URL/v1/link/token -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=refresh_token -d refresh_token=$REFRESH_TOKEN

# 2. Make the request.
curl $DARI_GATEWAY_URL/v1/chat/completions \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H "content-type: application/json" \
  -d '{"model": "dari/routing", "messages": [{"role": "user", "content": "Hi"}]}'
```

Example response data:

```json /v1/chat/completions response theme={null}
{
  "id": "chatcmpl-354c6713-7abc-49bb-949b-c02c8747c139",
  "object": "chat.completion",
  "model": "openai/gpt-5.5",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "Hi! How can I help?" },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 14, "completion_tokens": 8, "total_tokens": 22 },
  "dari_routing": {
    "requested_model": "dari/routing",
    "selected_model": "openai/gpt-5.5",
    "request_id": "354c6713-7abc-49bb-949b-c02c8747c139"
  }
}
```

### Next Steps

Congratulations, you have completed the Dari Link Quickstart! There are a few directions you can go in now:

Choose which plans and keys Link offers your users. See [What Users Can Connect](https://docs.dari.dev/link/what-users-can-connect.md).

Let users change what they shared, and handle a user who disconnects. See [Manage Connections](https://docs.dari.dev/link/manage-connections.md).

Running agents in sandboxes? Give each one its own short-lived token. See [Sandboxes And Workers](https://docs.dari.dev/link/sandboxes.md).

Read back what a run or a user used. See [Usage And Budgets](https://docs.dari.dev/link/usage-and-budgets.md).

Test the whole flow without a real subscription. See [Test Your Integration](https://docs.dari.dev/link/test-your-integration.md).

For every option and endpoint, see the [Link Web SDK](https://docs.dari.dev/link/web.md) and the [Link endpoints](https://docs.dari.dev/link/reference/http.md) reference.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.