diff --git a/docs/api-guide.mdx b/docs/api-guide.mdx index 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.json index 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.json index 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.mdx new file mode 100644 index 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 + + + The library identifier in the format `/owner/repo` (e.g., `/facebook/react`) + + + + + + Type of documentation to retrieve + - `code`: Code examples and API documentation + - `info`: Informational documentation and guides + + Default: `"code"` + + + + Format of the response + - `json`: Structured JSON with metadata + - `txt`: Plain text format + + Default: `"json"` + + + + Maximum number of snippets to return (1-100) + + + + Page number for pagination (starts at 1) + + + + Filter documentation by topic (e.g., "hooks", "components", "api") + + + + Specific version to retrieve documentation for (e.g., "18.0.0") + + + + + +## 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"`) + + + + + Plain text documentation content + + + + Total number of tokens in the content + + + + + + Current page number + + + Number of items per page + + + Total number of pages available + + + Whether there is a next page + + + Whether there is a previous page + + + + + + + +### JSON Format with Code Type (`format: "json"`, `mode: "code"`) + + + + + Array of code snippets + + + Title of the code snippet + + + Description of what the code does + + + Programming language (e.g., "typescript", "javascript") + + + Number of tokens in the code + + + Unique identifier for the code snippet + + + Title of the source page + + + List of code examples + + + Programming language + + + The actual code + + + + + + + + Total number of tokens across all snippets + + + + + + Current page number + + + Number of items per page + + + Total number of pages available + + + Whether there is a next page + + + Whether there is a previous page + + + + + + + + Authentication level used + + + + + + + +### JSON Format with Info Type (`format: "json"`, `mode: "info"`) + + + + + Array of informational snippets + + + Page identifier + + + Breadcrumb path to the content + + + The documentation content + + + Number of tokens in the content + + + + + + Total number of tokens + + + + Pagination information (same structure as code response) + + + + Response metadata (same structure as code response) + + + + + +## Examples + + +```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, +}); +``` + + + +## 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.mdx new file mode 100644 index 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 + + + The search query to find libraries + + +## Response + + + + + Array of library search results + + + Unique identifier for the library (e.g., "/facebook/react") + + + Display name of the library + + + Brief description of the library + + + Default branch name + + + ISO 8601 timestamp of last update + + + Current processing state of the library + + + Total number of tokens in documentation + + + Total number of code snippets + + + Number of GitHub stars + + + Trust score of the library + + + Benchmark score + + + Available versions + + + + + + + Authentication level used for the request + + + + + + +## Examples + + + ```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; + } +} +``` + + + +## 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.mdx new file mode 100644 index 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 + + + ```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 +``` + + + +## 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: , +}); +``` + + + The SDK checks for API keys in this order: 1. `config.apiKey` (if provided) 2. + `process.env.CONTEXT7_API_KEY` + + +## 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