---
title: "Code Examples"
description: "Ready-to-copy examples for quickstarts, search, pagination, error handling, and production patterns."
canonical_url: "https://www.scholarxiv.com/developers/docs/papers-api/examples"
markdown_url: "https://www.scholarxiv.com/developers/docs/papers-api/examples.md"
---

# Code Examples
URL: /developers/docs/papers-api/examples
LLM index: /llms.txt
Description: Ready-to-copy examples for quickstarts, search, pagination, error handling, and production patterns.

# Code Examples

All practical code samples for the Papers API in one place.

## Quick Start

```txt title="Base URL"
https://scholarxiv.com
```

<Tabs items={["cURL", "TypeScript"]}>
<Tab value="cURL">

```bash title="first-request.sh"
curl "https://scholarxiv.com/api/v1/papers/search?q=large+language+models&limit=5" \
  -H "Authorization: Bearer sxv_your_key_here"
```

</Tab>
<Tab value="TypeScript">

```ts title="example.ts"
import axios from 'axios';

const { data } = await axios.get('https://scholarxiv.com/api/v1/papers/search', {
  headers: { Authorization: `Bearer ${process.env.SCHOLARXIV_API_KEY}` },
  params: { q: 'large language models', limit: 5 }
});

console.log(data.data);
console.log(data.pagination);
```

</Tab>
</Tabs>

## Simple Search (GET)

```bash title="simple.sh"
curl "https://scholarxiv.com/api/v1/papers/search?q=attention+is+all+you+need&limit=3" \
  -H "Authorization: Bearer sxv_your_key"
```

```ts title="simple.ts"
import axios from 'axios';

const { data } = await axios.get('https://scholarxiv.com/api/v1/papers/search', {
  headers: { Authorization: `Bearer ${process.env.SCHOLARXIV_API_KEY}` },
  params: { q: 'attention is all you need', limit: 3 }
});
```

## Advanced Search (POST)

```bash title="advanced.sh"
curl "https://scholarxiv.com/api/v1/papers/search" \
  -X POST \
  -H "Authorization: Bearer sxv_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "searchFilterString": { "cat": "cs.CL", "abs": "evaluation" },
    "limit": 10,
    "sortBy": "submittedDate",
    "sortOrder": "descending"
  }'
```

```ts title="advanced.ts"
import axios from 'axios';

const { data } = await axios.post(
  'https://scholarxiv.com/api/v1/papers/search',
  {
    searchFilterString: { cat: 'cs.CL', abs: 'evaluation' },
    limit: 10,
    sortBy: 'submittedDate',
    sortOrder: 'descending'
  },
  {
    headers: {
      Authorization: `Bearer ${process.env.SCHOLARXIV_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);
```

## Pagination Loop

Always use the `nextPage` value returned by the API.

```ts title="pagination.ts"
import axios from 'axios';

const client = axios.create({
  baseURL: 'https://scholarxiv.com',
  headers: { Authorization: `Bearer ${process.env.SCHOLARXIV_API_KEY}` }
});

let page = 0;
const allPapers = [];

while (page !== null) {
  const { data } = await client.post('/api/v1/papers/search', {
    searchFilterString: { all: 'large language models', cat: 'cs.CL' },
    page,
    limit: 100
  });

  allPapers.push(...data.data);
  page = data.pagination.nextPage;
}

console.log(`Fetched ${allPapers.length} papers`);
```

## Rate Limit Retry (429)

```ts title="retry.ts"
async function searchWithBackoff(params: any, maxRetries = 3) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const res = await fetch(
      'https://scholarxiv.com/api/v1/papers/search?' + new URLSearchParams(params),
      { headers: { Authorization: `Bearer ${process.env.SCHOLARXIV_API_KEY}` } }
    );

    if (res.status !== 429) return res.json();

    const retryAfter = Number(res.headers.get('retry-after')) || 60;
    await new Promise(r => setTimeout(r, retryAfter * 1000));
  }
  throw new Error('Rate limit retries exhausted');
}
```

**Client-side 429 handling example:**

```ts
if (res.status === 429) {
  const retryAfter = res.headers.get('retry-after');
  console.warn(`Rate limited. Retry after ${retryAfter}s`);
  // implement backoff...
}
```

## Defensive Client Wrapper

```ts title="client.ts"
import axios from 'axios';

export async function searchPapers(filters: Record<string, string>, limit = 20) {
  const active = Object.fromEntries(
    Object.entries(filters).filter(([, v]) => typeof v === 'string' && v.trim())
  );

  if (Object.keys(active).length === 0) {
    throw new Error('Provide at least one search filter');
  }

  try {
    const { data } = await axios.post(
      'https://scholarxiv.com/api/v1/papers/search',
      { searchFilterString: active, limit },
      {
        headers: {
          Authorization: `Bearer ${process.env.SCHOLARXIV_API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );
    return data;
  } catch (err: any) {
    const message = axios.isAxiosError(err)
      ? err.response?.data?.error ?? err.message
      : err.message;
    throw new Error(`Papers API error: ${message}`);
  }
}
```

## Safe Logging (Auth Failures)

Never log full keys. Prefixes are safe and match what the dashboard shows.

```ts
const key = extractApiKey(req);
const prefix = key ? key.slice(0, 10) : 'none';
console.error(`Auth failed for key prefix ${prefix}`);
```

## Production Checklist

- Store keys only in environment variables
- Use separate keys per environment / service
- Drive all pagination from the `nextPage` value (never guess)
- Handle 429s with `Retry-After` + backoff (examples above)
- Monitor the Usage dashboard before large jobs or agent runs
- Put a thin server-side proxy in front of the API (hides secrets + allows caching)
- Rotate keys regularly (create → deploy → delete old)
- Add your own correlation IDs so you can trace calls in the dashboard logs

See the [Limits](/developers/docs/papers-api/limits) page for quota and plan change details.

## Related

- [Search](/developers/docs/papers-api/search) — filter reference and parameter details
- [Errors](/developers/docs/papers-api/errors) — full status code reference
- [Limits](/developers/docs/papers-api/limits) — entitlements, rolling windows, and downgrade behavior

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
Docs-scoped sitemap: [/docs/sitemap.md](/docs/sitemap.md).
Well-known sitemap: [/.well-known/sitemap.md](/.well-known/sitemap.md).
