Context7 Platform -- Up-to-date docs for AI agents
CTX7-855: Context7 TS SDK docs (#1080)
Fahreddin Özcan6d1e6442eef3
diff --git a/docs/api-guide.mdx b/docs/api-guide.mdxindex 9c1fcba4..048bde54 100644--- a/docs/api-guide.mdx+++ b/docs/api-guide.mdx@@ -194,6 +194,5 @@ const response = await fetch("https://context7.com/api/v2/docs/code/vercel/next.Authorization: "Bearer CONTEXT7_API_KEY",},});-const docs = await response.json();```diff --git a/docs/docs.json b/docs/docs.jsonindex 9e41ef5a..e983ae52 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -32,6 +32,21 @@"dashboard/billing"]},+ {+ "group": "SDKs",+ "pages": [+ {+ "group": "TypeScript",+ "pages": [+ "sdks/ts/getting-started",+ {+ "group": "Commands",+ "pages": ["sdks/ts/commands/search-library", "sdks/ts/commands/get-docs"]+ }+ ]+ }+ ]+ },{"group": "API Reference","openapi": "openapi.json"diff --git a/docs/openapi.json b/docs/openapi.jsonindex e30832ac..05f4fb57 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -728,6 +728,57 @@]}},+ "headers": {+ "X-Context7-Page": {+ "description": "Current page number (1-indexed). Only returned for text/plain responses (type=txt).",+ "schema": {+ "type": "integer",+ "minimum": 1+ },+ "example": 1+ },+ "X-Context7-Limit": {+ "description": "Number of items per page. Only returned for text/plain responses (type=txt).",+ "schema": {+ "type": "integer",+ "minimum": 1,+ "maximum": 10+ },+ "example": 10+ },+ "X-Context7-Total-Pages": {+ "description": "Total number of pages available. Only returned for text/plain responses (type=txt).",+ "schema": {+ "type": "integer",+ "minimum": 0+ },+ "example": 10+ },+ "X-Context7-Has-Next": {+ "description": "Whether a next page exists. Only returned for text/plain responses (type=txt).",+ "schema": {+ "type": "string",+ "enum": ["true", "false"]+ },+ "example": "true"+ },+ "X-Context7-Has-Prev": {+ "description": "Whether a previous page exists. Only returned for text/plain responses (type=txt).",+ "schema": {+ "type": "string",+ "enum": ["true", "false"]+ },+ "example": "false"+ },+ "X-Context7-Total-Tokens": {+ "description": "Total token count for the current page. Only returned for text/plain responses (type=txt).",+ "schema": {+ "type": "integer",+ "minimum": 0+ },+ "example": 1500+ }+ },"responses": {"CodeSnippetsJsonResponse": {"description": "Successful response with code snippets",@@ -801,10 +852,31 @@},"text/plain": {"schema": {- "type": "string"+ "type": "string",+ "description": "Plain text formatted documentation. Pagination metadata is returned via response headers."},"example": "### Create and Run Next.js App with create-next-app (Quick Start)\n\nSource: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/01-installation.mdx\n\nQuickly set up and start a new Next.js application using `create-next-app` with various package managers. This command creates a new project directory, installs dependencies, and starts the development server. The `--yes` flag skips interactive prompts, enabling a default setup with TypeScript, Tailwind, ESLint, App Router, and Turbopack.\n\n```bash\npnpm create next-app@latest my-app --yes\ncd my-app\npnpm dev\n```\n\n```bash\nnpx create-next-app@latest my-app --yes\ncd my-app\nnpm run dev\n```\n\n```bash\nyarn create next-app@latest my-app --yes\ncd my-app\nyarn dev\n```\n\n```bash\nbun create next-app@latest my-app --yes\ncd my-app\nbun dev\n```"}+ },+ "headers": {+ "X-Context7-Page": {+ "$ref": "#/components/headers/X-Context7-Page"+ },+ "X-Context7-Limit": {+ "$ref": "#/components/headers/X-Context7-Limit"+ },+ "X-Context7-Total-Pages": {+ "$ref": "#/components/headers/X-Context7-Total-Pages"+ },+ "X-Context7-Has-Next": {+ "$ref": "#/components/headers/X-Context7-Has-Next"+ },+ "X-Context7-Has-Prev": {+ "$ref": "#/components/headers/X-Context7-Has-Prev"+ },+ "X-Context7-Total-Tokens": {+ "$ref": "#/components/headers/X-Context7-Total-Tokens"+ }}},"InfoSnippetsJsonResponse": {@@ -859,10 +931,31 @@},"text/plain": {"schema": {- "type": "string"+ "type": "string",+ "description": "Plain text formatted documentation. Pagination metadata is returned via response headers."},"example": "### How to Contribute > Writing MDX\n\nSource: https://github.com/vercel/next.js/blob/canary/docs/04-community/01-contribution-guide.mdx\n\nThe docs are written in [MDX](https://mdxjs.com/), a markdown format that supports JSX syntax. This allows us to embed React components in the docs. See the [GitHub Markdown Guide](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) for a quick overview of markdown syntax."}+ },+ "headers": {+ "X-Context7-Page": {+ "$ref": "#/components/headers/X-Context7-Page"+ },+ "X-Context7-Limit": {+ "$ref": "#/components/headers/X-Context7-Limit"+ },+ "X-Context7-Total-Pages": {+ "$ref": "#/components/headers/X-Context7-Total-Pages"+ },+ "X-Context7-Has-Next": {+ "$ref": "#/components/headers/X-Context7-Has-Next"+ },+ "X-Context7-Has-Prev": {+ "$ref": "#/components/headers/X-Context7-Has-Prev"+ },+ "X-Context7-Total-Tokens": {+ "$ref": "#/components/headers/X-Context7-Total-Tokens"+ }}},"BadRequestError": {diff --git a/docs/sdks/ts/commands/get-docs.mdx b/docs/sdks/ts/commands/get-docs.mdxnew file mode 100644index 00000000..ee41024e--- /dev/null+++ b/docs/sdks/ts/commands/get-docs.mdx@@ -0,0 +1,415 @@+---+title: "Get Docs"+description: "Retrieve library documentation in various formats"+---++# Get Docs++Retrieve documentation for a specific library. You can get code examples or informational documentation in either JSON or text format.++## Arguments++<ParamField path="libraryId" type="string" required>+ The library identifier in the format `/owner/repo` (e.g., `/facebook/react`)+</ParamField>++<ParamField path="options" type="GetDocsOptions">+ <Expandable title="properties">+ <ParamField path="mode" type="'code' | 'info'">+ Type of documentation to retrieve+ - `code`: Code examples and API documentation+ - `info`: Informational documentation and guides++ Default: `"code"`+ </ParamField>++ <ParamField path="format" type="'json' | 'txt'">+ Format of the response+ - `json`: Structured JSON with metadata+ - `txt`: Plain text format++ Default: `"json"`+ </ParamField>++ <ParamField path="limit" type="number">+ Maximum number of snippets to return (1-100)+ </ParamField>++ <ParamField path="page" type="number">+ Page number for pagination (starts at 1)+ </ParamField>++ <ParamField path="topic" type="string">+ Filter documentation by topic (e.g., "hooks", "components", "api")+ </ParamField>++ <ParamField path="version" type="string">+ Specific version to retrieve documentation for (e.g., "18.0.0")+ </ParamField>++ </Expandable>+</ParamField>++## Response++The response type is automatically inferred based on the `format` and `mode` parameters. All response types extend a common base with pagination and token information.++### Text Format (`format: "txt"`)++<ResponseField name="TextDocsResponse" type="object">+ <Expandable title="properties">+ <ResponseField name="content" type="string" required>+ Plain text documentation content+ </ResponseField>++ <ResponseField name="totalTokens" type="number" required>+ Total number of tokens in the content+ </ResponseField>++ <ResponseField name="pagination" type="Pagination" required>+ <Expandable title="properties">+ <ResponseField name="page" type="number" required>+ Current page number+ </ResponseField>+ <ResponseField name="limit" type="number" required>+ Number of items per page+ </ResponseField>+ <ResponseField name="totalPages" type="number" required>+ Total number of pages available+ </ResponseField>+ <ResponseField name="hasNext" type="boolean" required>+ Whether there is a next page+ </ResponseField>+ <ResponseField name="hasPrev" type="boolean" required>+ Whether there is a previous page+ </ResponseField>+ </Expandable>+ </ResponseField>++ </Expandable>+</ResponseField>++### JSON Format with Code Type (`format: "json"`, `mode: "code"`)++<ResponseField name="CodeDocsResponse" type="object">+ <Expandable title="properties">+ <ResponseField name="snippets" type="CodeSnippet[]" required>+ Array of code snippets+ <Expandable title="CodeSnippet properties">+ <ResponseField name="codeTitle" type="string" required>+ Title of the code snippet+ </ResponseField>+ <ResponseField name="codeDescription" type="string" required>+ Description of what the code does+ </ResponseField>+ <ResponseField name="codeLanguage" type="string" required>+ Programming language (e.g., "typescript", "javascript")+ </ResponseField>+ <ResponseField name="codeTokens" type="number" required>+ Number of tokens in the code+ </ResponseField>+ <ResponseField name="codeId" type="string" required>+ Unique identifier for the code snippet+ </ResponseField>+ <ResponseField name="pageTitle" type="string" required>+ Title of the source page+ </ResponseField>+ <ResponseField name="codeList" type="CodeExample[]" required>+ List of code examples+ <Expandable title="CodeExample properties">+ <ResponseField name="language" type="string" required>+ Programming language+ </ResponseField>+ <ResponseField name="code" type="string" required>+ The actual code+ </ResponseField>+ </Expandable>+ </ResponseField>+ </Expandable>+ </ResponseField>++ <ResponseField name="totalTokens" type="number" required>+ Total number of tokens across all snippets+ </ResponseField>++ <ResponseField name="pagination" type="Pagination" required>+ <Expandable title="properties">+ <ResponseField name="page" type="number" required>+ Current page number+ </ResponseField>+ <ResponseField name="limit" type="number" required>+ Number of items per page+ </ResponseField>+ <ResponseField name="totalPages" type="number" required>+ Total number of pages available+ </ResponseField>+ <ResponseField name="hasNext" type="boolean" required>+ Whether there is a next page+ </ResponseField>+ <ResponseField name="hasPrev" type="boolean" required>+ Whether there is a previous page+ </ResponseField>+ </Expandable>+ </ResponseField>++ <ResponseField name="metadata" type="APIResponseMetadata" required>+ <Expandable title="properties">+ <ResponseField name="authentication" type="'none' | 'personal' | 'team'" required>+ Authentication level used+ </ResponseField>+ </Expandable>+ </ResponseField>++ </Expandable>+</ResponseField>++### JSON Format with Info Type (`format: "json"`, `mode: "info"`)++<ResponseField name="InfoDocsResponse" type="object">+ <Expandable title="properties">+ <ResponseField name="snippets" type="InfoSnippet[]" required>+ Array of informational snippets+ <Expandable title="InfoSnippet properties">+ <ResponseField name="pageId" type="string">+ Page identifier+ </ResponseField>+ <ResponseField name="breadcrumb" type="string">+ Breadcrumb path to the content+ </ResponseField>+ <ResponseField name="content" type="string" required>+ The documentation content+ </ResponseField>+ <ResponseField name="contentTokens" type="number" required>+ Number of tokens in the content+ </ResponseField>+ </Expandable>+ </ResponseField>++ <ResponseField name="totalTokens" type="number" required>+ Total number of tokens+ </ResponseField>++ <ResponseField name="pagination" type="Pagination" required>+ Pagination information (same structure as code response)+ </ResponseField>++ <ResponseField name="metadata" type="APIResponseMetadata" required>+ Response metadata (same structure as code response)+ </ResponseField>++ </Expandable>+</ResponseField>++## Examples++<RequestExample>+```typescript Code Docs (JSON - Default)+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7();++// JSON is the default format, no need to specify+const docs = await client.getDocs("/facebook/react", {+ mode: "code",+ limit: 5,+});++console.log(`Retrieved ${docs.snippets.length} code snippets`);+```++```typescript Code Docs (Text)+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7();++const docs = await client.getDocs("/facebook/react", {+ mode: "code",+ format: "txt",+ limit: 5,+});++console.log(docs.content);+```++```typescript Info Docs (Text)+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++const docs = await client.getDocs("/facebook/react", {+ mode: "info",+ format: "txt",+ limit: 3,+});++console.log(docs.content);+```++```typescript Info Docs (JSON)+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++const docs = await client.getDocs("/facebook/react", {+ mode: "info",+ format: "json",+ limit: 3,+});++docs.snippets.forEach((snippet) => {+ console.log(`Tokens: ${snippet.contentTokens}`);+});+```++```typescript With Pagination+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++const page1 = await client.getDocs("/facebook/react", {+ mode: "code",+ format: "json",+ page: 1,+ limit: 10,+});++console.log(`Page ${page1.pagination.page} of ${page1.pagination.totalPages}`);+console.log(`Has next: ${page1.pagination.hasNext}`);++if (page1.pagination.hasNext) {+ const page2 = await client.getDocs("/facebook/react", {+ mode: "code",+ format: "json",+ page: 2,+ limit: 10,+ });+ console.log(`Retrieved page 2 with ${page2.snippets.length} snippets`);+}+```++```typescript With Topic Filter+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++const hooks = await client.getDocs("/facebook/react", {+ mode: "code",+ format: "json",+ topic: "hooks",+ limit: 5,+});++console.log(`Found ${hooks.snippets.length} hook examples`);+```++```typescript With Version+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++const docs = await client.getDocs("/facebook/react", {+ mode: "code",+ format: "json",+ version: "18.0.0",+ limit: 5,+});+```++</RequestExample>++## Use Cases++### Building a Documentation Chat Bot++```typescript+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++async function getRelevantDocs(library: string, topic: string) {+ const docs = await client.getDocs(library, {+ mode: "code",+ format: "json",+ topic,+ limit: 5,+ });++ return docs.snippets.map((snippet) => ({+ title: snippet.codeTitle,+ description: snippet.codeDescription,+ code: snippet.codeList[0]?.code,+ language: snippet.codeLanguage,+ }));+}++const reactHooksDocs = await getRelevantDocs("/facebook/react", "hooks");+```++### Fetching All Documentation Pages++```typescript+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++async function getAllDocs(library: string) {+ const allSnippets = [];+ let page = 1;+ let hasMore = true;++ while (hasMore) {+ const response = await client.getDocs(library, {+ mode: "code",+ format: "json",+ page,+ limit: 100,+ });++ allSnippets.push(...response.snippets);+ hasMore = response.pagination.hasNext;+ page++;+ }++ return allSnippets;+}++const allReactDocs = await getAllDocs("/facebook/react");+console.log(`Total snippets: ${allReactDocs.length}`);+```++### Extracting Code Examples++```typescript+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++const docs = await client.getDocs("/facebook/react", {+ mode: "code",+ format: "json",+ limit: 20,+});++const tsExamples = docs.snippets+ .filter((snippet) => snippet.codeLanguage === "typescript")+ .map((snippet) => snippet.codeList)+ .flat();++console.log(`Found ${tsExamples.length} TypeScript examples`);+```diff --git a/docs/sdks/ts/commands/search-library.mdx b/docs/sdks/ts/commands/search-library.mdxnew file mode 100644index 00000000..ba498080--- /dev/null+++ b/docs/sdks/ts/commands/search-library.mdx@@ -0,0 +1,153 @@+---+title: "Search Library"+description: "Search available libraries"+---++# Search Library++Search across available libraries. Returns finalized public libraries and accessible private repositories based on authentication.++## Arguments++<ParamField path="query" type="string" required>+ The search query to find libraries+</ParamField>++## Response++<ResponseField name="SearchLibraryResponse" type="object">+ <Expandable title="properties">+ <ResponseField name="results" type="SearchResult[]" required>+ Array of library search results+ <Expandable title="SearchResult properties">+ <ResponseField name="id" type="string" required>+ Unique identifier for the library (e.g., "/facebook/react")+ </ResponseField>+ <ResponseField name="title" type="string" required>+ Display name of the library+ </ResponseField>+ <ResponseField name="description" type="string" required>+ Brief description of the library+ </ResponseField>+ <ResponseField name="branch" type="string" required>+ Default branch name+ </ResponseField>+ <ResponseField name="lastUpdateDate" type="string" required>+ ISO 8601 timestamp of last update+ </ResponseField>+ <ResponseField+ name="state"+ type="'initial' | 'finalized' | 'processing' | 'error' | 'delete'"+ required+ >+ Current processing state of the library+ </ResponseField>+ <ResponseField name="totalTokens" type="number" required>+ Total number of tokens in documentation+ </ResponseField>+ <ResponseField name="totalSnippets" type="number" required>+ Total number of code snippets+ </ResponseField>+ <ResponseField name="stars" type="number">+ Number of GitHub stars+ </ResponseField>+ <ResponseField name="trustScore" type="number">+ Trust score of the library+ </ResponseField>+ <ResponseField name="benchmarkScore" type="number">+ Benchmark score+ </ResponseField>+ <ResponseField name="versions" type="string[]">+ Available versions+ </ResponseField>+ </Expandable>+ </ResponseField>+ <ResponseField name="metadata" type="APIResponseMetadata" required>+ <Expandable title="properties">+ <ResponseField name="authentication" type="'none' | 'personal' | 'team'" required>+ Authentication level used for the request+ </ResponseField>+ </Expandable>+ </ResponseField>+ </Expandable>+</ResponseField>++## Examples++<RequestExample>+ ```typescript Basic Search+ import { Context7 } from "@upstash/context7-sdk";++const client = new Context7();++const response = await client.searchLibrary("react");++console.log(`Found ${response.results.length} libraries`);+response.results.forEach(library => {+console.log(`${library.title}: ${library.description}`);+});++````++```typescript Error Handling+import { Context7, Context7Error } from "@upstash/context7-sdk";++const client = new Context7();++try {+ const response = await client.searchLibrary("express");++ if (response.results.length === 0) {+ console.log("No libraries found");+ } else {+ console.log(`Found ${response.results.length} libraries`);+ }+} catch (error) {+ if (error instanceof Context7Error) {+ console.error("API Error:", error.message);+ } else {+ throw error;+ }+}+```++</RequestExample>++## Use Cases++### Finding Popular Libraries++```typescript+const response = await client.searchLibrary("react");++// Sort by stars+const popular = response.results+ .filter((lib) => lib.stars !== undefined)+ .sort((a, b) => (b.stars || 0) - (a.stars || 0));++console.log("Most popular:", popular[0].title);+```++### Checking Documentation Availability++```typescript+const response = await client.searchLibrary("axios");++response.results.forEach((lib) => {+ console.log(`${lib.title}:`);+ console.log(` - State: ${lib.state}`);+ console.log(` - Snippets: ${lib.totalSnippets}`);+ console.log(` - Tokens: ${lib.totalTokens}`);+});+```++### Getting Library Versions++```typescript+const response = await client.searchLibrary("lodash");++const library = response.results[0];+if (library.versions) {+ console.log(`Available versions: ${library.versions.join(", ")}`);+}+```diff --git a/docs/sdks/ts/getting-started.mdx b/docs/sdks/ts/getting-started.mdxnew file mode 100644index 00000000..22ba1e01--- /dev/null+++ b/docs/sdks/ts/getting-started.mdx@@ -0,0 +1,139 @@+---+title: "Getting Started"+description: "Get started with the Context7 TypeScript SDK"+---++# Getting Started++`@upstash/context7-sdk` is a TypeScript SDK for Context7, enabling easier access to library documentation with full type coverage.++Using `@upstash/context7-sdk` you can:++- Search across available libraries+- Retrieve code documentation with contextual examples+- Fetch informational documentation and guides+- Access library metadata and versioning information+- Filter documentation by topic and pagination++You can find the Github Repository [here](https://github.com/upstash/context7/tree/master/packages/sdk).++## Install++<CodeGroup>+ ```shell npm+ npm install @upstash/context7-sdk+ ```++```shell pnpm+pnpm add @upstash/context7-sdk+```++```shell yarn+yarn add @upstash/context7-sdk+```++```shell bun+bun add @upstash/context7-sdk+```++</CodeGroup>++## Usage++### Initializing the Client++To use the Context7 SDK, you need an API key. You can get your API key from the [Context7 Dashboard](https://context7.com/dashboard).++#### Using environment variables++The SDK automatically reads from environment variables if no API key is provided in the config:++```bash+CONTEXT7_API_KEY="your_api_key_here"+```++When an environment variable is set, you can initialize the client without any parameters:++```typescript+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7();+```++#### Using a configuration object++If you prefer to pass configuration in code, the constructor accepts a config object containing the apiKey value. This could be useful if your application needs to interact with multiple projects, each with a different configuration.++```typescript+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: <CONTEXT7_API_KEY>,+});+```++<Note>+ The SDK checks for API keys in this order: 1. `config.apiKey` (if provided) 2.+ `process.env.CONTEXT7_API_KEY`+</Note>++## Quick Start Example++```typescript+import { Context7 } from "@upstash/context7-sdk";++const client = new Context7();++const searchResponse = await client.searchLibrary("react");+console.log(`Found ${searchResponse.results.length} libraries`);++// Get code documentation (JSON is the default format)+const codeDocs = await client.getDocs("/facebook/react", {+ mode: "code",+ limit: 5,+});++console.log(`Retrieved ${codeDocs.snippets.length} code snippets`);+console.log(`Total tokens: ${codeDocs.totalTokens}`);++// Get info documentation as text+const textDocs = await client.getDocs("/facebook/react", {+ mode: "info",+ format: "txt",+ limit: 3,+});++console.log(textDocs.content);+```++## Error Handling++The SDK throws `Context7Error` for API errors:++```typescript+import { Context7, Context7Error } from "@upstash/context7-sdk";++const client = new Context7({+ apiKey: process.env.CONTEXT7_API_KEY!,+});++try {+ const docs = await client.getDocs("/invalid/library", {+ mode: "code",+ format: "txt",+ });+} catch (error) {+ if (error instanceof Context7Error) {+ console.error("Context7 API Error:", error.message);+ } else {+ console.error("Unexpected error:", error);+ }+}+```++## Next Steps++Explore the SDK commands:++- [Search Library](/sdks/ts/commands/search-library) - Search for libraries+- [Get Docs](/sdks/ts/commands/get-docs) - Retrieve library documentation