================ CODE SNIPPETS ================ ### Example cURL Request for Brave Suggest API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/suggest Demonstrates how to make a GET request to the Brave Suggest API using cURL, including query parameters for 'q', 'country', and 'count', and required headers for 'Accept', 'Accept-Encoding', and 'X-Subscription-Token'. ```Shell curl -s --compressed "https://api.search.brave.com/res/v1/suggest/search?q=hello&country=US&count=5" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Perform a Basic News Search with cURL Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/news-search/get-started This cURL example demonstrates how to make a GET request to the Brave News Search API. It includes common query parameters like 'q' for query, 'count' for results limit, 'country', 'search_lang', and 'spellcheck', along with necessary 'Accept' and 'X-Subscription-Token' headers for authentication and response format. ```shell curl -s --compressed "https://api.search.brave.com/res/v1/news/search?q=munich&count=10&country=us&search_lang=en&spellcheck=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Example CURL Request for Brave Spellcheck API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/spellcheck This example demonstrates how to make a GET request to the Brave Spellcheck API using cURL. It includes query parameters for the search term and country, along with essential headers for content type, encoding, and API key authentication. ```curl curl -s --compressed "https://api.search.brave.com/res/v1/spellcheck/search?q=helo&country=US" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Integrate Brave Search API with OpenAI Python SDK Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/get-started This snippet demonstrates how to use the Brave Search API's OpenAI-compatible endpoint (`/res/v1/chat/completions`) with the OpenAI Python SDK. It shows how to initialize the client with your API key and base URL, then make a chat completion request to get an AI-summarized answer based on a user query. Ensure you have the `openai` library installed and replace `` with your actual key. ```Python from openai import OpenAI client = OpenAI( api_key="", base_url="https://api.search.brave.com/res/v1", ) completions = client.chat.completions.create( messages=[ { "role": "user", "content": "What are the best things to do in Paris with kids?", } ], model="brave-pro", stream=False, ) print(completions.choices[0].message.content) ``` -------------------------------- ### Example CURL Request for Brave Suggest API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/suggest/get-started Demonstrates how to make a GET request to the Brave Suggest API using cURL. This example includes common query parameters like 'q' for the query, 'country', and 'count', along with required headers for authentication ('X-Subscription-Token') and content negotiation ('Accept', 'Accept-Encoding'). ```shell curl -s --compressed "https://api.search.brave.com/res/v1/suggest/search?q=hello&country=US&count=5" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Install Python Dependencies for Brave Summarizer API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/code-samples This command installs the necessary Python libraries, `aiohttp` for asynchronous HTTP requests and `aiolimiter` for rate limiting, required to interact with the Brave Search Summarizer API. Ensure you have Python 3 installed on your machine before running this command. ```bash pip install aiohttp aiolimiter ``` -------------------------------- ### Perform Initial Web Search with Summary Request using cURL Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/get-started This cURL command demonstrates how to make an initial request to the Brave Web Search API endpoint. It includes the 'q' parameter for the search query and 'summary=1' to indicate that a summary is desired if eligible. The request requires 'Accept' and 'X-Subscription-Token' headers for proper authentication and response formatting. ```Shell curl -s --compressed "https://api.search.brave.com/res/v1/web/search?q=what+is+the+second+highest+mountain&summary=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Brave Suggest API Endpoint Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/suggest The base URL for the Brave Suggest Search API, used to generate potential suggestions for a given query. ```APIDOC https://api.search.brave.com/res/v1/suggest/search ``` -------------------------------- ### Fetch AI-Generated Location Descriptions with Brave Local Search API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/index This `curl` command demonstrates how to fetch AI-generated descriptions for specific locations using their `id` values via the Brave Local Search API. Multiple IDs can be included in the request. Ensure your API key is correctly set. ```Shell curl -s --compressed "https://api.search.brave.com/res/v1/local/descriptions?ids=1520066f3f39496780c5931d9f7b26a6&ids=d00b153c719a427ea515f9eacf4853a2" \ -H "accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "x-subscription-token: " ``` -------------------------------- ### Example cURL Request for Brave Web Search API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/web-search This cURL command demonstrates how to make a basic GET request to the Brave Web Search API. It queries for 'brave search' and includes necessary headers for content negotiation and API key authentication. Replace with your actual subscription token. ```bash curl -s --compressed "https://api.search.brave.com/res/v1/web/search?q=brave+search" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Brave Summarizer Search API Endpoints Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/get-started This section lists the various API endpoints available for the Brave Summarizer Search API. These endpoints facilitate different types of data retrieval, including general web search, specific summarizer functions, and chat completions. ```APIDOC https://api.search.brave.com/res/v1/web/search https://api.search.brave.com/res/v1/summarizer/search https://api.search.brave.com/res/v1/summarizer/summary https://api.search.brave.com/res/v1/summarizer/summary_streaming https://api.search.brave.com/res/v1/summarizer/title https://api.search.brave.com/res/v1/summarizer/enrichments https://api.search.brave.com/res/v1/summarizer/followups https://api.search.brave.com/res/v1/summarizer/entity_info https://api.search.brave.com/res/v1/chat/completions ``` -------------------------------- ### Understand Brave Summarizer Key Response Format Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/get-started This JSON snippet illustrates the structure of the 'summarizer' key returned in the Web Search API response. This key is essential for subsequent requests to poll for summarized content. It contains critical details such as the original query, country, language, safesearch settings, and a results hash. ```JSON { "summarizer": { "type": "summarizer", "key": "{\"query\": \"what is the second highest mountain\", \"country\": \"us\", \"language\": \"en\", \"safesearch\": \"moderate\", \"results_hash\": \"a51e129180225a2f4fe1a00984bcbf58f0ae0625c97723aae43c2c6e3440715b}" } } ``` -------------------------------- ### Brave News Search API Endpoint Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/news-search/get-started This is the base URL for the Brave News Search API, which allows retrieval of news articles relevant to a specified query. It serves as the primary access point for all news search operations. ```APIDOC https://api.search.brave.com/res/v1/news/search ``` -------------------------------- ### Brave Web Search API Request Example Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/index Example cURL request to the Brave Web Search API for a general search query. Includes necessary headers for authentication and response formatting. ```APIDOC curl -s --compressed "https://api.search.brave.com/res/v1/web/search?q=brave+search" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### CURL Example for Brave Image Search API Request Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search This example demonstrates how to make a basic GET request to the Brave Image Search API using CURL. It includes common query parameters like 'q' for query, 'safesearch', 'count', 'search_lang', 'country', and 'spellcheck', along with required headers for content negotiation and authentication. Replace with your actual API key. ```CURL curl -s --compressed "https://api.search.brave.com/res/v1/images/search?q=munich&safesearch=strict&count=20&search_lang=en&country=us&spellcheck=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Install Express.js Dependency for Node.js Server Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides This command installs Express.js, a minimal and flexible Node.js web application framework, as a project dependency. Express is crucial for building the server-side component that will handle API requests and serve static files, simplifying routing and middleware management. ```Bash npm install express --save ``` -------------------------------- ### Poll Brave Summarizer Endpoint for Summarized Content using cURL Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/get-started This cURL command shows how to use the 'summarizer' key obtained from the initial web search response to poll the Brave Summarizer API endpoint. The key must be URL-encoded when passed as a parameter. Requests to this summarizer endpoint are not billed; only the initial web search request incurs charges based on your selected plan. ```Shell curl -s --compressed "https://api.search.brave.com/res/v1/summarizer/search?key=%7B%22query%22%3A%22what%20is%20the%20second%20highest%20mountain%22%2C%22country%22%3A%22us%22%2C%22language%22%3A%22en%22%2C%22safesearch%22%3A%22moderate%22%2C%22results_hash%22%3A%22a51e129180225a2f4fe1a00984bcbf58f0ae0625c97723aae43c2c6e3440715b%22%7D&entity_info=1" \ -H "accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "x-subscription-token: " ``` -------------------------------- ### Brave Spellcheck API Endpoint Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/spellcheck This is the base URL for the Brave Spellcheck API, used to submit queries for spell correction. It is part of the Brave Search API suite. ```APIDOC https://api.search.brave.com/res/v1/spellcheck/search ``` -------------------------------- ### Fetch Location Points of Interest (POIs) with Brave Local Search API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/index This `curl` command shows how to use retrieved location `id` values to fetch additional Points of Interest (POIs) from the Brave Local Search API. Multiple IDs can be provided in a comma-separated list. Remember to use your valid API key. ```Shell curl -s --compressed "https://api.search.brave.com/res/v1/local/pois?ids=1520066f3f39496780c5931d9f7b26a6&ids=d00b153c719a427ea515f9eacf4853a2" \ -H "accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "x-subscription-token: " ``` -------------------------------- ### Execute Node.js Application for Brave Image Search Client Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides This shell command initiates the Node.js server for the image search client by running `index.js`. It requires Node.js to be installed and the `index.js` file to be correctly configured in the project directory. Upon successful execution, the application becomes accessible, typically via `localhost:4000/images.html` in a web browser. ```Shell node index.js ``` -------------------------------- ### Set Up Project Structure for Brave Image Search Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides This command-line snippet creates the necessary directory structure and empty files for the image search application. It establishes the `img-search` root, a `public` folder for static assets, and placeholder files for HTML and CSS, preparing the environment for development. ```Bash mkdir img-search && cd img-search mkdir public touch public/images.html touch public/styles.css ``` -------------------------------- ### Brave Local Search API - Location Result Example Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/index Example JSON response snippet from the Brave Local Search API, showing a list of locations with their respective IDs and titles. ```APIDOC { "locations": { "results": [ { "id": "1520066f3f39496780c5931d9f7b26a6", "title": "Pangea Banquet Mediterranean Food" }, { "id": "d00b153c719a427ea515f9eacf4853a2", "title": "Park Mediterranean Grill" }, { "id": "4b943b378725432aa29f019def0f0154", "title": "The Halal Mediterranean Co." } ] } } ``` -------------------------------- ### HowTo API Schema Definition Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/web-search/responses Defines the structure for aggregated information on a 'how-to' guide. This schema includes fields for the instructional text, an optional name, a URL, and a list of associated image URLs. ```APIDOC interface HowTo { text: string; // The how to text. (Required) name?: string; // A name for the how to. url?: string; // A URL associated with the how to. image?: string[]; // A list of image URLs associated with the how to. } ``` -------------------------------- ### Run Brave Summarizer API Python Script Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/code-samples This command executes the `summarizer.py` Python script, which fetches summarized results from the Brave Search Summarizer API. Before running, ensure your API key is configured within the script and that you are subscribed to the Pro AI plan. ```bash python summarizer.py ``` -------------------------------- ### Example JSON Response with Summarizer Key Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search This JSON snippet illustrates the structure of the 'summarizer' object found within the Web Search API response. It provides a 'key' that is essential for subsequent requests to the summarizer endpoint to retrieve the actual summarized content. ```JSON { "summarizer": { "type": "summarizer", "key": "{\"query\": \"what is the second highest mountain\", \"country\": \"us\", \"language\": \"en\", \"safesearch\": \"moderate\", \"results_hash\": \"a51e129180225a2f4fe1a00984bcbf58f0ae0625c97723aae43c2c6e3440715b}" } } ``` -------------------------------- ### Perform a Video Search with cURL Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/video-search/get-started This example demonstrates how to make a basic video search request using cURL. It queries for 'munich' videos, limits the count to 10, specifies 'us' country, 'en' search language, and enables spellcheck. Remember to replace with your actual subscription token. ```cURL curl -s --compressed "https://api.search.brave.com/res/v1/videos/search?q=munich&count=10&country=us&search_lang=en&spellcheck=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### JavaScript: Fetch Images from API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides This snippet demonstrates how to make an asynchronous GET request to the `/api/images` endpoint. It constructs a URL with a query parameter and parses the JSON response. This function is a core dependency for retrieving image data. ```javascript async function fetchImages(query) { const params = new URLSearchParams({ q: query }); const response = await fetch(`/api/images?${params}`); return await response.json(); } ``` -------------------------------- ### Brave Local Search API - Fetching AI Descriptions Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/index Example cURL request to retrieve AI-generated descriptions for specific locations using their IDs from the Brave Local Search API. ```APIDOC curl -s --compressed "https://api.search.brave.com/res/v1/local/descriptions?ids=1520066f3f39496780c5931d9f7b26a6&ids=d00b153c719a427ea515f9eacf4853a2" \ -H "accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "x-subscription-token: " ``` -------------------------------- ### Python Script for Brave Summarizer API Integration Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/code-samples This comprehensive Python script demonstrates how to fetch summarized results from the Brave Search Summarizer API. It includes asynchronous HTTP requests using `aiohttp`, rate limiting with `aiolimiter`, API key configuration, and error handling for both web search and summarizer endpoints. Remember to replace `"your_api_key"` with your actual Brave Search API key. ```python import asyncio import json import logging from urllib.parse import urljoin from aiohttp import ClientSession, ClientTimeout, TCPConnector from aiolimiter import AsyncLimiter # Configure logger logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) log = logging.getLogger(__name__) # Request rate and concurrency API_MAX_CONCURRENT_REQUESTS = 1 API_RPS = 1 API_RATE_LIMIT = AsyncLimiter(API_RPS, 1) API_TIMEOUT = 20 # Brave Search API Key API_KEY = "your_api_key" # Brave Search API host API_HOST = "https://api.search.brave.com" # Brave Search API subpaths API_PATH = { "web": urljoin(API_HOST, "res/v1/web/search"), "summarizer_search": urljoin(API_HOST, "res/v1/summarizer/search"), } # Create request headers for specific endpoints API_HEADERS = { "web": {"X-Subscription-Token": API_KEY, "Api-Version": "2023-10-11"}, "summarizer": {"X-Subscription-Token": API_KEY, "Api-Version": "2024-04-23"}, } # Create web search request params API_PARAMS_WEB = { "q": "what is the second highest mountain", "summary": 1, } async def get_summary(session: ClientSession) -> None: # Fetch web search results so we can get a summary key async with session.get( API_PATH["web"], params=API_PARAMS_WEB, headers=API_HEADERS["web"], ) as response: log.info("Querying url: [%s]", response.url) # print(await response.text()) data = await response.json() status = response.status if status != 200: log.error( "Failure getting web search results \n%s", json.dumps(data, indent=2), ) return # Get the summary key from web search results summary_key = data.get("summarizer", {}).get("key") if not summary_key: log.error("Failure: Getting summary key") return log.info("Summarizer Key: [%s]", summary_key) # Fetch summary all in one log.info("Requesting summarizer search in blocking mode") async with session.get( url=API_PATH["summarizer_search"], params={"key": summary_key, "entity_info": 1}, headers=API_HEADERS["summarizer"], ) as response: log.info("Querying url: [%s]", response.url) data = await response.json() status = response.status log.info(json.dumps(data, indent=2)) async def main(): async with API_RATE_LIMIT: async with ClientSession( connector=TCPConnector(limit=API_MAX_CONCURRENT_REQUESTS), timeout=ClientTimeout(API_TIMEOUT), ) as session: await get_summary(session=session) asyncio.run(main()) ``` -------------------------------- ### Summarizer Search API Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/request-headers This section outlines all supported request headers for the Brave Summarizer Search API. Each header entry specifies its requirement status, official name, and a detailed description, including usage examples for headers like User-Agent. ```APIDOC [ { "header": "Accept", "required": false, "name": "Accept", "description": "The default supported media type is `application/json`" }, { "header": "Accept-Encoding", "required": false, "name": "Accept Encoding", "description": "The supported compression type is `gzip`." }, { "header": "Api-Version", "required": false, "name": "Web Search API Version", "description": "The Brave Web Search API version to use. This is denoted by the format `YYYY-MM-DD`. The latest version is used by default, and the previous ones can be found in the [API Changelog](./api-changelog)." }, { "header": "Cache-Control", "required": false, "name": "Cache Control", "description": "Search will return cached web search results by default. To prevent caching, set the Cache-Control header to `no-cache`. This is currently done as best effort." }, { "header": "User-Agent", "required": false, "name": "User Agent", "description": "The user agent of the client sending the request. Search can utilize the user agent to provide a different experience depending on the client sending the request. The user agent should follow the commonly used browser agent strings on each platform. For more information on curating user agents, see [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-user-agent). User agent string examples by platform: \n* **Android**: Mozilla/5.0 (Linux; Android 13; Pixel 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36\n* **iOS**: Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1\n* **macOS**: Mozilla/5.0 (Macintosh; Intel Mac OS X 12_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/\n* **Windows**: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" }, { "header": "X-Subscription-Token", "required": true, "name": "Authentication token", "description": "The secret token for the subscribed plan to authenticate the request. Can be obtained from [API Keys](/app/keys)." } ] ``` -------------------------------- ### Example CURL Request for Brave Image Search API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/get-started This `curl` command demonstrates how to make a basic request to the Brave Image Search API. It queries for 'munich' images, sets strict safe search, limits results to 20, specifies English language and US country, and enables spellcheck. Remember to replace `` with your actual subscription token. ```curl curl -s --compressed "https://api.search.brave.com/res/v1/images/search?q=munich&safesearch=strict&count=20&search_lang=en&country=us&spellcheck=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Brave Video Search API: Example cURL Request for Video Search Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/video-search This cURL command demonstrates how to perform a basic video search query using the Brave Video Search API. It requires an API key ("X-Subscription-Token") for authentication and returns results in JSON format. Replace "" with your actual subscription token. ```bash curl -s --compressed "https://api.search.brave.com/res/v1/videos/search?q=munich&count=10&country=us&search_lang=en&spellcheck=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Image Search API Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/request-headers This section provides a detailed reference for all request headers used with the Brave Image Search API. Each header's purpose, whether it's required, and specific examples or accepted values are outlined. ```APIDOC Header: Accept Required: false Name: Accept Description: The default supported media type is application/json ``` ```APIDOC Header: Accept-Encoding Required: false Name: Accept Encoding Description: The supported compression type is gzip. ``` ```APIDOC Header: Api-Version Required: false Name: Web Search API Version Description: The Brave Web Search API version to use. This is denoted by the format YYYY-MM-DD. The latest version is used by default, and the previous ones can be found in the API Changelog. ``` ```APIDOC Header: Cache-Control Required: false Name: Cache Control Description: Search will return cached web search results by default. To prevent caching, set the Cache-Control header to no-cache. This is currently done as best effort. ``` ```APIDOC Header: User-Agent Required: false Name: User Agent Description: The user agent of the client sending the request. Search can utilize the user agent to provide a different experience depending on the client sending the request. The user agent should follow the commonly used browser agent strings on each platform. For more information on curating user agents, see RFC 9110 (https://www.rfc-editor.org/rfc/rfc9110.html#name-user-agent). User agent string examples by platform: * Android: Mozilla/5.0 (Linux; Android 13; Pixel 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36 * iOS: Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1 * macOS: Mozilla/5.0 (Macintosh; Intel Mac OS X 12_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ * Windows: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ ``` ```APIDOC Header: X-Subscription-Token Required: true Name: Authentication token Description: The secret token for the subscribed plan to authenticate the request. Can be obtained from API Keys. ``` -------------------------------- ### Brave Local Search API - Fetching Location Details Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/index Example cURL request to fetch details for specific locations using their IDs from the Brave Local Search API. Supports batching multiple IDs. ```APIDOC curl -s --compressed "https://api.search.brave.com/res/v1/local/pois?ids=1520066f3f39496780c5931d9f7b26a6&ids=d00b153c719a427ea515f9eacf4853a2" \ -H "accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "x-subscription-token: " ``` -------------------------------- ### Perform a Spellcheck Request with cURL Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/spellcheck/get-started This cURL command demonstrates how to make a basic GET request to the Brave Spellcheck API. It includes query parameters for the text to be spell-checked ('q') and the target country ('country'), along with necessary HTTP headers for content type, encoding, and API authentication using your subscription token. ```bash curl -s --compressed "https://api.search.brave.com/res/v1/spellcheck/search?q=helo&country=US" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Global Response Headers for Brave Web Search API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/web-search/response-headers This section details the standard response headers returned by the Brave Web Search API. It covers headers like X-RateLimit-Limit, X-RateLimit-Policy, X-RateLimit-Remaining, and X-RateLimit-Reset, providing their purpose, format, and example values for effective API usage and quota management. ```APIDOC [ { "header": "X-RateLimit-Limit", "name": "Rate Limit", "description": "Rate limits associated with the requested plan. An example rate limit `X-RateLimit-Limit: 1, 15000` means 1 request per second and 15000 requests per month." }, { "header": "X-RateLimit-Policy", "name": "Rate Limit Policy", "description": "Rate limit policies currently associated with the requested plan. An example policy `X-RateLimit-Policy: 1;w=1, 15000;w=2592000` means a limit of 1 request over a 1 second window and 15000 requests over a month window. The windows are always given in seconds." }, { "header": "X-RateLimit-Remaining", "name": "Rate Limit Remaining", "description": "Remaining quota units associated with the expiring limits. An example remaining limit `X-RateLimit-Remaining: 1, 1000` indicates the API is able to be accessed once during the current second, and 1000 times over the current month. **Note**: Only successful requests are counted and billed." }, { "header": "X-RateLimit-Reset", "name": "Rate Limit Reset", "description": "The number of seconds until the quota associated with the expiring limits resets. An example reset limit `X-RateLimit-Reset: 1, 1419704` means a single request can be done again in a second and in 1419704 seconds the full monthly quota associated with the plan will be available again." } ] ``` -------------------------------- ### Query Brave News Search API with cURL Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/news-search This cURL command demonstrates a basic GET request to the Brave News Search API. It includes query parameters for search term, result count, country, and language, along with necessary 'Accept' and 'X-Subscription-Token' headers. Replace with your valid API key. ```bash curl -s --compressed "https://api.search.brave.com/res/v1/news/search?q=munich&count=10&country=us&search_lang=en&spellcheck=1" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Brave Video Search API Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/video-search/request-headers This section details the various request headers available for the Brave Video Search API. It outlines whether each header is required, its purpose, and provides examples or specific values where applicable. Understanding these headers is crucial for correctly formatting API requests. ```APIDOC { "VideoSearchAPIRequestHeaders": { "Accept": { "required": false, "name": "Accept", "description": "The default supported media type is `application/json`" }, "Accept-Encoding": { "required": false, "name": "Accept Encoding", "description": "The supported compression type is `gzip`." }, "Api-Version": { "required": false, "name": "Web Search API Version", "description": "The Brave Web Search API version to use. This is denoted by the format `YYYY-MM-DD`. The latest version is used by default, and the previous ones can be found in the [API Changelog](./api-changelog)." }, "Cache-Control": { "required": false, "name": "Cache Control", "description": "Search will return cached web search results by default. To prevent caching, set the Cache-Control header to `no-cache`. This is currently done as best effort." }, "User-Agent": { "required": false, "name": "User Agent", "description": "The user agent of the client sending the request. Search can utilize the user agent to provide a different experience depending on the client sending the request. The user agent should follow the commonly used browser agent strings on each platform. For more information on curating user agents, see [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-user-agent). User agent string examples by platform: * **Android**: Mozilla/5.0 (Linux; Android 13; Pixel 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36\n* **iOS**: Mozilla/5.0 (iPhone; CPU iPhone OS 15\_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1\n* **macOS**: Mozilla/5.0 (Macintosh; Intel Mac OS X 12\_0\_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/\n* **Windows**: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" }, "X-Subscription-Token": { "required": true, "name": "Authentication token", "description": "The secret token for the subscribed plan to authenticate the request. Can be obtained from [API Keys](/app/keys)." } } } ``` -------------------------------- ### APIDOC: GET /api/images Endpoint Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides Documentation for the `/api/images` endpoint used to retrieve image search results. This endpoint supports a query parameter and returns a JSON object containing an array of image results, each with thumbnail details and a title. ```json { "endpoint": "/api/images", "method": "GET", "description": "Fetches images based on a search query.", "parameters": [ { "name": "q", "type": "string", "description": "The search query for images." } ], "response": { "type": "object", "properties": { "results": { "type": "array", "description": "An array of image results.", "items": { "type": "object", "properties": { "image": { "type": "object", "properties": { "thumbnail": { "type": "object", "properties": { "src": { "type": "string", "description": "URL of the image thumbnail." }, "width": { "type": "number", "description": "Width of the thumbnail." }, "height": { "type": "number", "description": "Height of the thumbnail." } }, "required": ["src", "width", "height"] }, "title": { "type": "string", "description": "Title or alt text of the image." } }, "required": ["thumbnail", "title"] } }, "required": ["image"] } } }, "required": ["results"] } } ``` -------------------------------- ### HTML: Basic Image Search Page Structure Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides This HTML snippet provides the foundational structure for the image search interface. It includes an input field for search queries, a button to trigger the search, and a `div` element where the fetched and rendered images will be displayed. The JavaScript functions are integrated via inline event handlers. ```html
``` -------------------------------- ### Summarizer Search API Global Response Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/summarizer-search/response-headers This section provides a detailed reference for all global response headers returned by the Brave Summarizer Search API. Each header's name, purpose, and example values are described to help developers understand API rate limits and quota management. ```APIDOC Response Headers: Global: - Header: X-RateLimit-Limit Name: Rate Limit Description: Rate limits associated with the requested plan. An example rate limit "X-RateLimit-Limit: 1, 15000" means 1 request per second and 15000 requests per month. - Header: X-RateLimit-Policy Name: Rate Limit Policy Description: Rate limit policies currently associated with the requested plan. An example policy "X-RateLimit-Policy: 1;w=1, 15000;w=2592000" means a limit of 1 request over a 1 second window and 15000 requests over a month window. The windows are always given in seconds. - Header: X-RateLimit-Remaining Name: Rate Limit Remaining Description: Remaining quota units associated with the expiring limits. An example remaining limit "X-RateLimit-Remaining: 1, 1000" indicates the API is able to be accessed once during the current second, and 1000 times over the current month. Note: Only successful requests are counted and billed. - Header: X-RateLimit-Reset Name: Rate Limit Reset Description: The number of seconds until the quota associated with the expiring limits resets. An example reset limit "X-RateLimit-Reset: 1, 1419704" means a single request can be done again in a second and in 1419704 seconds the full monthly quota associated with the plan will be available again. ``` -------------------------------- ### Implement Node.js Express Proxy for Brave Image API Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/image-search/guides This JavaScript code defines a Node.js Express server that acts as a proxy for the Brave Search Image API. It handles GET requests to `/api/images`, constructs API parameters, and makes a `fetch` call to the Brave API, including the necessary `x-subscription-token` header. The server then forwards the API response to the client, effectively bypassing Cross-Origin Resource Sharing (CORS) issues. Remember to replace `` with your actual Brave API subscription token. ```JavaScript const express = require('express'); const app = express(); const port = 4000; app.use(express.static('public')); const API_KEY = ''; const API_PATH = 'https://api.search.brave.com/res/v1/images/search'; app.get('/api/images', async (req, res) => { try { const params = new URLSearchParams({ q: req.query.q, count: 20, search_lang: 'en', country: 'us', spellcheck: 1, }); const response = await fetch(`${API_PATH}?${params}`, { headers: { 'x-subscription-token': API_KEY, accept: 'application/json' } }); const data = await response.json(); res.json(data); return; } catch (err) { console.log(err); } res.status(500).send('Internal Server Error'); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); ``` -------------------------------- ### Brave Web Search API Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/web-search/request-headers This snippet details the request headers for the Brave Web Search API. It outlines each header's name, whether it's required, its purpose, and provides examples for some. Providing more header information, such as client location, can enhance search result relevance. ```APIDOC {"type": "API_HEADERS_REFERENCE", "description": "This object describes the request headers for the Brave Web Search API.", "headers": [{"header_name": "Accept", "required": false, "display_name": "Accept", "description": "The default supported media type is `application/json`.", "type": "string", "example": "application/json"}, {"header_name": "Accept-Encoding", "required": false, "display_name": "Accept Encoding", "description": "The supported compression type is `gzip`.", "type": "string", "example": "gzip"}, {"header_name": "Api-Version", "required": false, "display_name": "Web Search API Version", "description": "The Brave Web Search API version to use. This is denoted by the format `YYYY-MM-DD`. The latest version is used by default, and the previous ones can be found in the API Changelog.", "type": "string", "format": "YYYY-MM-DD"}, {"header_name": "Cache-Control", "required": false, "display_name": "Cache Control", "description": "Search will return cached web search results by default. To prevent caching, set the Cache-Control header to `no-cache`. This is currently done as best effort.", "type": "string", "enum": ["no-cache"]}, {"header_name": "User-Agent", "required": false, "display_name": "User Agent", "description": "The user agent of the client sending the request. Search can utilize the user agent to provide a different experience depending on the client sending the request. The user agent should follow the commonly used browser agent strings on each platform. For more information on curating user agents, see RFC 9110 (https://www.rfc-editor.org/rfc/rfc9110.html#name-user-agent). User agent string examples by platform:\n* Android: Mozilla/5.0 (Linux; Android 13; Pixel 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36\n* iOS: Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1\n* macOS: Mozilla/5.0 (Macintosh; Intel Mac OS X 12_0_0) AppleWebKit/537.3 ``` -------------------------------- ### Understand Brave Search API URL Versioning (v1) Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/general The Brave Search API uses a major version prefix in the URL, such as 'v1'. This version is rarely updated and signifies a major API redesign, requiring significant upgrades from users. ```APIDOC API URL Format: /v1/web/search Description: This major version (e.g., 'v1') is prefixed to the API URL. It is intended for significant API redesigns and is expected to change only rarely, necessitating a major upgrade path. ``` -------------------------------- ### Understand Brave Search API URL Versioning (v1) Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/general/api-versioning The Brave Search API uses a major versioning scheme prefixed to the API URL, such as '/v1/web/search'. This 'v1' version is rarely changed and is reserved for major API redesigns, which would necessitate a significant upgrade path for users. ```HTTP /v1/web/search ``` -------------------------------- ### Identify Brave Search API Backwards Compatible Changes Source: https://api-dashboard.search.brave.com/app/documentation/web-search/get-started/general/api-versioning Brave Search considers certain API modifications to be backwards compatible, meaning they do not require any action from the API user. These changes ensure continued functionality without breaking existing integrations. ```APIDOC - Adding new optional request parameters or headers to APIs that already exist. - Adding new properties to an existing API response. - Adding new API resources. - Changing the order of properties in an existing API response. - Changing the length and format of string values. e.g. object IDs, urls, display strings. ```