# stackexchange.top_by_tag

**stable** **Advanced**

Top-voted questions for a tag.

`GET /v1/stackexchange/top_by_tag`

## What you get

A list of Stack Exchange results in Onekey's unified shape, in `data` (an array). An empty array is a normal, successful answer and is charged like any other; a source that reports "nothing found" as an error returns a free `404 not_found` instead.

## What it costs

- **Advanced · 5 credits** for a fresh fetch, charged only when it succeeds.
- **Free when served from cache (0.2 credit for a cached response over 100 KB).**
- **Free** if the request is invalid (never charged) or the source fails or reports not found (refunded).

## Parameters

| Name | Type | Required | Default | What it is | Constraints |
| --- | --- | --- | --- | --- | --- |
| `tag` | string | yes | (required) | Tag, e.g. python | max 35 chars; must match `[a-z0-9][a-z0-9.#+_-]{0,34}`; trimmed, lowercased |
| `site` | string | no | - | Stack Exchange site, default stackoverflow | max 41 chars; must match `[a-z][a-z.]{1,40}`; trimmed, lowercased |

## Request

```bash
curl "https://api.onekey.dev/v1/stackexchange/top_by_tag?tag=python" \
  -H "x-api-key: YOUR_API_KEY"
```

```python
import requests

res = requests.get(
    "https://api.onekey.dev/v1/stackexchange/top_by_tag",
    params={"tag": "python"},
    headers={"x-api-key": "YOUR_API_KEY"},
)
body = res.json()

if body["success"]:
    print(body["data"])
else:
    print(body["error"]["code"], body["error"]["message"])
```

```javascript
const params = new URLSearchParams({ tag: "python" });
const res = await fetch(`https://api.onekey.dev/v1/stackexchange/top_by_tag?${params}`, {
  headers: { "x-api-key": "YOUR_API_KEY" },
});
const body = await res.json();

if (body.success) console.log(body.data);
else console.error(body.error.code, body.error.message);
```

## Recorded response

A real Stack Exchange response, recorded and returned in Onekey's shape. Fields the platform does not provide are `null`.

```json
{
  "success": true,
  "data": [
    {
      "content": {
        "id": "231767",
        "title": "What does the \"yield\" keyword do in Python?",
        "url": "https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python",
        "text": null,
        "createdAt": "2008-10-23T22:21:11Z"
      },
      "entity": {
        "name": "python"
      },
      "engagement": {
        "likes": 13135,
        "comments": 51,
        "views": 3499972
      },
      "author": {
        "id": "18300",
        "username": "Alex. S.",
        "url": "https://stackoverflow.com/users/18300/alex-s",
        "avatarUrl": "https://i.sstatic.net/jcyI4.jpg?s=256",
        "reputation": 148444
      }
    },
    {
      "content": {
        "id": "419163",
        "title": "What does if __name__ == \"__main__\": do?",
        "url": "https://stackoverflow.com/questions/419163/what-does-if-name-main-do",
        "text": null,
        "createdAt": "2009-01-07T04:11:00Z"
      },
      "entity": {
        "name": "python"
      },
      "engagement": {
        "likes": 8442,
        "comments": 40,
        "views": 5043293
      },
      "author": {
        "id": "51518",
        "username": "Devoted",
        "url": "https://stackoverflow.com/users/51518/devoted",
        "avatarUrl": "https://www.gravatar.com/avatar/eb5a95cb1be342c4089183cd8232a7f2?s=256&d=identicon&r=PG",
        "reputation": 185051
      }
    }
  ],
  "metadata": {
    "platform": "stackexchange",
    "endpoint": "top_by_tag",
    "cached": false,
    "stale": false,
    "age_s": 0,
    "fetched_at": "2026-01-01T12:00:00+00:00",
    "credits_charged": 5,
    "request_id": "7f3a9c2e5b1d4c8fa2e6d0b9c4f18e37"
  },
  "error": null
}
```

## Field mapping

How this endpoint's source fields become Onekey's [unified schema](https://onekey.dev/docs/schema.md). Fields the source lacks come back as `null`.

| Source path | Onekey field | Transform |
| --- | --- | --- |
| `question_id` | `content.id` | `toString` |
| `title` | `content.title` | `htmlUnescape` |
| `link` | `content.url` | `safeUrl` |
| `body` | `content.text` | `stripHtml` |
| `creation_date` | `content.createdAt` | `toIsoDate` |
| `tags.0` | `entity.name` | - |
| `score` | `engagement.likes` | `toNumber` |
| `answer_count` | `engagement.comments` | `toNumber` |
| `view_count` | `engagement.views` | `toNumber` |
| `owner.user_id` | `author.id` | `toString` |
| `owner.display_name` | `author.username` | `htmlUnescape` |
| `owner.link` | `author.url` | `safeUrl` |
| `owner.profile_image` | `author.avatarUrl` | `safeUrl` |
| `owner.reputation` | `author.reputation` | `toNumber` |

## Caching and freshness

- Fresh for about 2 minutes. Repeat calls in that window are served from cache and are free.
- Between 2 minutes and 15 minutes the cached copy is still served instantly and marked `stale: true` while Onekey refreshes it in the background.
- If the source is down when a refresh is needed, the last copy can be served for up to 1 hour more (marked stale).
- A "not found" is remembered for 1 minute and is free.
- The cache is shared across all customers, which is what keeps repeat calls cheap.

## What can go wrong

| Status | Code | What to do |
| --- | --- | --- |
| 401 | `unauthorized` | Check the `x-api-key` header. |
| 402 | `insufficient_credits` | [Add credits](https://onekey.dev/pricing); your balance must cover the price. |
| 404 | `not_found` | Unknown endpoint path. |
| 422 | `invalid_params` | Fix the parameters using the table above. Free. |
| 429 | `rate_limited` | Wait `Retry-After` seconds, then retry. |
| 502 | `upstream_error` | The source failed. Refunded; retry with backoff. |

See [Errors](https://onekey.dev/docs/errors.md) for the full list and retry guidance.

Status: stable (verified against the live source).
