Skip to content

Context7 Platform -- Up-to-date docs for AI agents

CTX7-2818: Document the Search API (#3210)

Fahreddin Özcan06b320a36c11
diff --git a/docs/api-guide.mdx b/docs/api-guide.mdx
index 08875da8..63603f44 100644
--- a/docs/api-guide.mdx
+++ b/docs/api-guide.mdx
@@ -18,6 +18,7 @@ Get your API key at [context7.com/dashboard](https://context7.com/dashboard). Le
| Method | Endpoint | Description |
|--------|----------|-------------|
+| [Search Documentation](/api-reference/search/search-documentation) | `GET /api/v3/search` | Find relevant documentation without resolving a library first |
| [Search Library](/api-reference/search/search-for-libraries) | `GET /api/v2/libs/search` | Find libraries by name |
| [Get Context](/api-reference/context/get-documentation-context) | `GET /api/v2/context` | Retrieve documentation snippets for a library |
| [Refresh Library](/api-reference/refresh/refresh-a-library) | `POST /api/v1/refresh` | Refresh a library's documentation |
@@ -61,7 +62,11 @@ You can pin a specific version with either `/owner/repo/<version>` or `/owner/re
Don't know the ID for a library? Find it on [context7.com](https://context7.com) — the URL path of the library page **is** the ID. Or call [Search Library](/api-reference/search/search-for-libraries) and use the `id` from the response.
</Tip>
-### Complete Workflow Example
+### Search documentation in one request
+
+The Search API is the simplest way to retrieve documentation. You provide a question, and Context7 selects relevant libraries before searching and reranking their snippets.
+
+If no documentation matches, Search returns `404 no_documentation_found`; treat it as an empty result. A temporary search failure returns `503 search_failed` and can be retried.
```python
import os
@@ -69,22 +74,59 @@ import requests
headers = {"Authorization": f"Bearer {os.environ['CONTEXT7_API_KEY']}"}
-# Step 1: Search for the library
+# Context7 selects the library and returns the best snippets
+response = requests.get(
+ "https://context7.com/api/v3/search",
+ headers=headers,
+ params={
+ "query": "How do I stream an OpenAI response from a Next.js route?",
+ "library": ["Next.js", "OpenAI"],
+ "language": "TypeScript",
+ "type": "json",
+ },
+)
+response.raise_for_status()
+docs = response.json()
+
+for snippet in docs["codeSnippets"]:
+ print(f"Library: {snippet['libraryId']}")
+ print(f"Title: {snippet['codeTitle']}")
+ for code in snippet["codeList"]:
+ print(f"Code: {code['code'][:200]}...")
+
+for info in docs["infoSnippets"]:
+ print(f"Content: {info['content'][:200]}...")
+```
+
+Library hints are optional and do not need to be exact. You can provide up to four names or exact Context7 library IDs. Use `version` with at least one library hint, and use `language` when you want language-specific examples to rank higher.
+
+### Choose a library yourself
+
+Use Search Library followed by Get Context when your application needs to inspect or choose a specific documentation source.
+
+```python
+import os
+import requests
+
+headers = {"Authorization": f"Bearer {os.environ['CONTEXT7_API_KEY']}"}
+
+# Find libraries that match the task
search_response = requests.get(
"https://context7.com/api/v2/libs/search",
headers=headers,
- params={"libraryName": "react", "query": "I need to manage state"}
+ params={"libraryName": "react", "query": "I need to manage state"},
)
-data = search_response.json()
-best_match = data["results"][0]
+search_response.raise_for_status()
+best_match = search_response.json()["results"][0]
print(f"Found: {best_match['title']} ({best_match['id']})")
-# Step 2: Get documentation context
+# Request documentation from the selected library
context_response = requests.get(
"https://context7.com/api/v2/context",
headers=headers,
- params={"libraryId": best_match["id"], "query": "How do I use useState?", "type": "json"}
+ params={"libraryId": best_match["id"], "query": "How do I use useState?", "type": "json"},
)
+context_response.raise_for_status()
docs = context_response.json()
for snippet in docs["codeSnippets"]:
@@ -97,7 +139,11 @@ for info in docs["infoSnippets"]:
```
<Info>
- For TypeScript SDK usage, see [Search Library](/sdks/ts/commands/search-library) and [Get Context](/sdks/ts/commands/get-context).
+ Each Search API call counts as one request. The two-step flow makes two API calls when it searches for a library and then retrieves its documentation.
+</Info>
+
+<Info>
+ For TypeScript SDK usage, see [Search](/sdks/ts/commands/search), [Search Library](/sdks/ts/commands/search-library), and [Get Context](/sdks/ts/commands/get-context).
</Info>
## Rate Limits
@@ -135,6 +181,19 @@ curl "https://context7.com/api/v2/context?libraryId=/websites/uploadcare&query=i
-H "Authorization: Bearer CONTEXT7_API_KEY"
```
+### Add hints only when they provide useful context
+
+Start with only the question when the relevant library is clear from the task. Add library hints when a name is ambiguous or when the answer needs documentation from more than one product.
+
+```bash
+curl -G "https://context7.com/api/v3/search" \
+ -H "Authorization: Bearer CONTEXT7_API_KEY" \
+ --data-urlencode "query=How do I stream an OpenAI response from a Next.js route?" \
+ --data-urlencode "library=Next.js" \
+ --data-urlencode "library=OpenAI" \
+ --data-urlencode "language=TypeScript"
+```
+
### Cache Responses
Documentation updates are relatively infrequent, so caching responses for several hours or days reduces API calls and improves performance.
diff --git a/docs/docs.json b/docs/docs.json
index 41e750b7..d8e94201 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -198,7 +198,11 @@
{
"group": "Commands",
"expanded": false,
- "pages": ["sdks/ts/commands/search-library", "sdks/ts/commands/get-context"]
+ "pages": [
+ "sdks/ts/commands/search",
+ "sdks/ts/commands/search-library",
+ "sdks/ts/commands/get-context"
+ ]
}
]
},
diff --git a/docs/openapi.json b/docs/openapi.json
index a964095e..f1a0ef87 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -17,6 +17,131 @@
}
],
"paths": {
+ "/v3/search": {
+ "get": {
+ "summary": "Search documentation in one request",
+ "description": "Select up to four relevant Context7 libraries, retrieve their documentation in parallel, deduplicate and globally rerank the evidence, and return one bounded response. Optional library, version, and language values improve routing and ranking.",
+ "operationId": "searchDocumentation",
+ "tags": [
+ "Search"
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/QueryParam"
+ },
+ {
+ "$ref": "#/components/parameters/TypeParam"
+ },
+ {
+ "name": "library",
+ "in": "query",
+ "description": "Optional library hints. Repeat for up to four values; each may be a fuzzy product name such as `next.js` or an exact Context7 ID such as `/vercel/next.js`.",
+ "required": false,
+ "style": "form",
+ "explode": true,
+ "schema": {
+ "type": "array",
+ "maxItems": 4,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120
+ }
+ },
+ "example": [
+ "next.js",
+ "react"
+ ]
+ },
+ {
+ "name": "version",
+ "in": "query",
+ "description": "Optional version constraint. Requires at least one library value. It is strict when one library is provided and contextual when multiple libraries are provided.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "pattern": "^v?[0-9]+([._][0-9]+){0,2}([-+][a-zA-Z0-9.-]+)?$"
+ },
+ "example": "15.2"
+ },
+ {
+ "name": "language",
+ "in": "query",
+ "description": "Optional programming-language preference used for library selection, retrieval, and reranking. This is a soft preference and does not exclude language-neutral documentation.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 40
+ },
+ "example": "TypeScript"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Bounded documentation evidence from the selected libraries",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SearchContextResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "$ref": "#/components/responses/BadRequestError"
+ },
+ "401": {
+ "$ref": "#/components/responses/UnauthorizedError"
+ },
+ "402": {
+ "$ref": "#/components/responses/SpendingLimitError"
+ },
+ "404": {
+ "description": "No documentation matched the question or library hints",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ },
+ "example": {
+ "error": "no_documentation_found",
+ "message": "No documentation library matched the request. Check the library hint or name."
+ }
+ }
+ }
+ },
+ "429": {
+ "$ref": "#/components/responses/RateLimitError"
+ },
+ "503": {
+ "description": "Documentation search could not be completed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ },
+ "example": {
+ "error": "search_failed",
+ "message": "The documentation search could not be completed."
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {},
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/v2/libs/search": {
"get": {
"summary": "Search for libraries",
@@ -1509,6 +1634,50 @@
}
}
},
+ "LibraryHintParam": {
+ "name": "library",
+ "in": "query",
+ "description": "A library name or exact Context7 library ID. Repeat this parameter to search up to four libraries. Names do not need to be exact.",
+ "required": false,
+ "style": "form",
+ "explode": true,
+ "schema": {
+ "type": "array",
+ "maxItems": 4,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120
+ }
+ },
+ "example": [
+ "Next.js",
+ "OpenAI"
+ ]
+ },
+ "VersionParam": {
+ "name": "version",
+ "in": "query",
+ "description": "A version to use when selecting and ranking documentation. At least one library hint is required. With one library, Context7 targets that version. With multiple libraries, the version is treated as a preference for compatible candidates.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "pattern": "^v?\\d+(?:[._]\\d+){0,2}(?:[-+][a-z0-9.-]+)?$"
+ },
+ "example": "15.4.0"
+ },
+ "LanguageParam": {
+ "name": "language",
+ "in": "query",
+ "description": "A programming language to prefer when selecting and ranking snippets. This is a soft preference, so product documentation can still be returned when a language-specific snippet is unavailable.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 40
+ },
+ "example": "TypeScript"
+ },
"TypeParam": {
"name": "type",
"in": "query",
@@ -1808,6 +1977,112 @@
"infoSnippets"
]
},
+ "SearchCodeSnippet": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CodeSnippet"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "libraryId": {
+ "type": "string",
+ "description": "Context7 library ID that produced this snippet"
+ }
+ },
+ "required": [
+ "libraryId"
+ ]
+ }
+ ]
+ },
+ "SearchInfoSnippet": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/InfoSnippet"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "libraryId": {
+ "type": "string",
+ "description": "Context7 library ID that produced this snippet"
+ }
+ },
+ "required": [
+ "libraryId"
+ ]
+ }
+ ]
+ },
+ "SearchContextResponse": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ContextResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "codeSnippets": {
+ "type": "array",
+ "description": "Relevant code snippets with their selected library",
+ "items": {
+ "$ref": "#/components/schemas/SearchCodeSnippet"
+ }
+ },
+ "infoSnippets": {
+ "type": "array",
+ "description": "Relevant documentation snippets with their selected library",
+ "items": {
+ "$ref": "#/components/schemas/SearchInfoSnippet"
+ }
+ },
+ "rules": {
+ "type": "object",
+ "description": "Optional global rules and library-scoped guidelines",
+ "properties": {
+ "global": {
+ "type": "array",
+ "description": "Global team rules that apply to every returned library",
+ "items": {
+ "type": "string"
+ }
+ },
+ "libraries": {
+ "type": "array",
+ "description": "Rules scoped to a specific returned library",
+ "items": {
+ "type": "object",
+ "properties": {
+ "libraryId": {
+ "type": "string"
+ },
+ "libraryOwn": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "libraryTeam": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "libraryId",
+ "libraryOwn",
+ "libraryTeam"
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
+ },
"Error": {
"type": "object",
"description": "Standard error response",
diff --git a/docs/sdks/ts/commands/search.mdx b/docs/sdks/ts/commands/search.mdx
new file mode 100644
index 00000000..30f95d54
--- /dev/null
+++ b/docs/sdks/ts/commands/search.mdx
@@ -0,0 +1,105 @@
+---
+title: "Search"
+description: "Find relevant documentation without resolving a library first"
+---
+
+# Search
+
+Search Context7 documentation in one request. Context7 selects relevant libraries, searches them in parallel, and returns the best snippets together.
+
+The SDK returns structured JSON by default, consistent with its other methods. Set `type` to `txt` when you need plain text for an LLM prompt. The REST endpoint defaults to text unless you request `type=json`.
+
+## Arguments
+
+<ParamField path="query" type="string" required>
+ The question or task to search for. Specific, natural language questions produce the best results.
+</ParamField>
+
+<ParamField path="options" type="SearchOptions">
+ <Expandable title="properties">
+ <ParamField path="libraries" type="string[]">
+ Up to four library names or Context7 library IDs. These hints narrow the search when you already know which products are relevant.
+ </ParamField>
+ <ParamField path="version" type="string">
+ A version to search. Provide at least one library hint. With one library hint, the version is strict and Search returns 404 if no matching tag exists. With multiple libraries, it is a contextual preference.
+ </ParamField>
+ <ParamField path="language" type="string">
+ A programming language to prefer when ranking snippets, such as `TypeScript` or `Python`. This is a preference, so Context7 can still return product documentation when a language-specific snippet is unavailable.
+ </ParamField>
+ <ParamField path="type" type="'json' | 'txt'">
+ The response format. The SDK default is `json`.
+ </ParamField>
+ <ParamField path="signal" type="AbortSignal">
+ An abort signal for cancelling this request.
+ </ParamField>
+ <ParamField path="timeout" type="number | false">
+ A timeout in milliseconds for this request. Use `false` to disable the client timeout.
+ </ParamField>
+ <ParamField path="cache" type="CacheSetting">
+ A native fetch cache mode. Use `false` to omit the cache option.
+ </ParamField>
+ </Expandable>
+</ParamField>
+
+## Text response
+
+```typescript
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+const context = await client.search(
+ "How do I validate a request body with a schema?",
+ { type: "txt" }
+);
+
+console.log(context);
+```
+
+## JSON response
+
+JSON responses return a `SearchResponse` object with `codeSnippets`, `infoSnippets`, and optional `rules`. Each snippet includes the `libraryId` that it came from.
+
+```typescript
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+const result = await client.search(
+ "How do I stream an OpenAI response from a Next.js route?",
+ {
+ libraries: ["Next.js", "OpenAI"],
+ language: "TypeScript",
+ }
+);
+
+for (const snippet of result.codeSnippets) {
+ console.log(snippet.libraryId, snippet.codeTitle);
+ console.log(snippet.codeList);
+}
+
+for (const snippet of result.infoSnippets) {
+ console.log(snippet.libraryId, snippet.content);
+}
+
+console.log(result.rules);
+```
+
+## Version-specific search
+
+Use a library hint with `version` when your question depends on a particular release.
+
+```typescript
+const context = await client.search(
+ "How do I cache the result of a server function?",
+ {
+ libraries: ["Next.js"],
+ version: "15.4.0",
+ language: "TypeScript",
+ }
+);
+```
+
+Library names do not need to be exact. Use a Context7 library ID when you need to select a specific documentation source.
+
+If nothing matches, `client.search()` throws `Context7Error` with status 404. A temporary search failure returns status 503 and follows the SDK retry policy.