### Python: Install Dependencies & Run Brave Summarizer API Script Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search/code-samples These shell commands guide you through setting up your Python environment for the Brave Search Summarizer API. First, install `aiohttp` and `aiolimiter` for asynchronous HTTP requests and rate limiting. Then, execute the `summarizer.py` script to fetch summarized content. Ensure Python 3 is installed and your API key is updated in the script. ```Shell pip install aiohttp aiolimiter ``` ```Shell python summarizer.py ``` -------------------------------- ### Example cURL Request for Brave Suggest API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/suggest/get-started This cURL command demonstrates how to make a basic request to the Brave Suggest API. It includes common query parameters like 'q' for the query, 'country', and 'count', along with essential headers such as 'Accept', 'Accept-Encoding', and 'X-Subscription-Token' for authentication. ```curl 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: " ``` -------------------------------- ### Example CURL Request for Brave Suggest API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/suggest This example demonstrates how to make a GET request to the Brave Suggest API using the CURL command-line tool. It includes essential query parameters like 'q' for the query, 'country' for the region, and 'count' for the number of suggestions, along with required HTTP headers such as 'Accept', 'Accept-Encoding', and 'X-Subscription-Token' for authentication. ```bash 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: " ``` -------------------------------- ### Execute Image Search Client with Node.js Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/guides This command initiates the image search client application by running the `index.js` file using Node.js. It starts the local server, making the application accessible via `localhost:4000/images.html` in a web browser. Ensure Node.js is installed and `index.js` is configured as the main entry point. ```Bash node index.js ``` -------------------------------- ### Python: Brave Search Summarizer API Asynchronous Client Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search/code-samples This asynchronous Python script demonstrates how to interact with the Brave Search Summarizer API. It uses `aiohttp` for efficient network operations and `aiolimiter` to manage request rates. The script first queries the web search endpoint to obtain a summary key, then uses this key to retrieve a detailed summary. A valid Brave API key and a Pro AI subscription are required for successful execution. ```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()) ``` -------------------------------- ### Example CURL Request for Brave Video Search API Integration Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/video-search/get-started This example demonstrates a basic GET request to the Brave Video Search API using cURL. It showcases how to include essential query parameters like 'q', 'count', 'country', 'search_lang', and 'spellcheck', along with necessary 'Accept' and 'X-Subscription-Token' headers for authentication and response formatting. This snippet helps developers quickly test and understand API interaction. ```shell 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: " ``` -------------------------------- ### Install Node.js Express Dependency for Server Source: https://api-dashboard.search.brave.com/app/documentation/suggest/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 creating the server that will handle API calls and serve static files, effectively preventing Cross-Origin Resource Sharing (CORS) issues. ```Shell npm install express --save ``` -------------------------------- ### Perform a Web Search API Request with cURL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search This example demonstrates how to make a basic GET request to the Brave Web Search API using cURL. It queries for 'brave search' and sets 'Accept' and 'Accept-Encoding' headers, requiring an API key for authentication. This snippet illustrates a complete, runnable example for interacting with the API. ```Shell 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 Suggest API Endpoint URL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/suggest This is the base URL for the Brave Suggest Search API, which provides functionality to generate potential search suggestions for a given query. It is the entry point for all Suggest API requests. ```URL https://api.search.brave.com/res/v1/suggest/search ``` -------------------------------- ### Brave Suggest API Endpoint Definition Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/suggest/get-started This snippet provides the base URL for the Brave Suggest Search API. This endpoint is used to generate potential search suggestions for a given query, forming the foundation for all suggest API requests. ```APIDOC https://api.search.brave.com/res/v1/suggest/search ``` -------------------------------- ### Perform a Web Search API Request with cURL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/get-started This example demonstrates how to make a basic GET request to the Brave Web Search API using cURL. It queries for 'brave search' and expects a JSON response, requiring an API key for authentication. ```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: " ``` -------------------------------- ### Example CURL Request for Brave Video Search API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/video-search This cURL command demonstrates a basic GET request to the Brave Video Search API. It includes query parameters for search term, count, country, and language, along with necessary headers for content negotiation and API key authentication. ```shell 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: " ``` -------------------------------- ### Execute a CURL Request to Brave Web Search API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/index This example demonstrates how to make a basic GET request to the Brave Web Search API using cURL. It includes necessary headers for accepting JSON and gzip encoding, and requires a valid X-Subscription-Token for authentication. Replace with your actual API key. ```shell 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: " ``` -------------------------------- ### API Schema: HowTo Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/responses Provides aggregated information for a 'how-to' guide, including its text, name, URL, and associated images. This schema is used for instructional content. ```APIDOC class HowTo { text: string (required) - The how to text. name: string (optional) - A name for the how to. url: string (optional) - A URL associated with the how to. image: list (optional) - A list of image URLs associated with the how to. } ``` -------------------------------- ### Create Project Directory and Files for Image Search Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/guides This shell snippet demonstrates how to set up the basic directory structure for the image search project. It creates the main project folder, a 'public' directory for static assets, and placeholder files for HTML and CSS, providing the foundational organization for the application. ```Shell mkdir img-search && cd img-search mkdir public touch public/images.html touch public/styles.css ``` -------------------------------- ### Query Brave Search API with OpenAI SDK in Python Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search/get-started This Python snippet demonstrates how to use the OpenAI SDK to interact with Brave Search's OpenAI-compatible endpoint. It shows how to initialize the client with your API key and base URL, construct a chat completion request with a user query, and print the AI-generated response. This example requires the `openai` library. ```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) ``` -------------------------------- ### Brave Summarizer API: Example Summarizer Key Response (JSON) Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search/get-started This JSON snippet illustrates the typical response structure from the Web Search API when a query is eligible for summarization. It contains the 'summarizer' object, which includes a 'key' that must be used to fetch the full summarized content from the dedicated summarizer endpoint. ```JSON { "summarizer": { "type": "summarizer", "key": "{\"query\": \"what is the second highest mountain\", \"country\": \"us\", \"language\": \"en\", \"safesearch\": \"moderate\", \"results_hash\": \"a51e129180225a2f4fe1a00984bcbf58f0ae0625c97723aae43c2c6e3440715b}" } } ``` -------------------------------- ### Brave Search API: Request URL Versioning Example Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/general/api-versioning Demonstrates the major versioning scheme where 'v1' is prefixed to the API URL, indicating significant API redesigns. Users should expect this version to change rarely, primarily for major architectural shifts. ```APIDOC /v1/web/search ``` -------------------------------- ### Example cURL Request for Brave Spellcheck API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/spellcheck This cURL command demonstrates how to make a GET request to the Brave Spellcheck API, including required headers and query parameters. It queries for 'helo' and specifies the country as US. Remember to replace '' with your actual subscription token. ```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: " ``` -------------------------------- ### Brave Suggest API Global Response Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/suggest/response-headers This section provides a detailed reference for the global response headers returned by the Brave Suggest Search API, including their purpose, format, and examples for understanding rate limiting and quota status. ```APIDOC { "headers": [ { "name": "X-RateLimit-Limit", "displayName": "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." }, { "name": "X-RateLimit-Policy", "displayName": "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." }, { "name": "X-RateLimit-Remaining", "displayName": "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." }, { "name": "X-RateLimit-Reset", "displayName": "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." } ] } ``` -------------------------------- ### Brave News Search API Endpoint Reference Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/news-search/get-started This is the primary endpoint for accessing the Brave News Search API. It allows clients to send GET requests to retrieve news articles relevant to a specified query. No specific dependencies are required beyond a valid API key for authentication. ```URL https://api.search.brave.com/res/v1/news/search ``` -------------------------------- ### Example cURL Request for Brave Image Search API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search This cURL command demonstrates a typical request to the Brave Image Search API. It queries for 'munich' images, applies strict safe search, limits results to 20, specifies English language and US country, and enables spellcheck. Authentication is handled via the 'X-Subscription-Token' header. ```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: " ``` -------------------------------- ### Execute Brave News Search API Request with cURL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/news-search/get-started This cURL command demonstrates how to query the Brave News Search API for news related to 'munich'. It requires a valid API key, passed via the 'X-Subscription-Token' header, and expects a JSON response. The example specifies query parameters for count, country, search language, and spellcheck, returning news articles matching the criteria. ```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: " ``` -------------------------------- ### Brave Web Search API Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/request-headers This section details the request headers for the Brave Web Search API, outlining their purpose, whether they are required, and examples where applicable. Providing more header information can enhance search result relevance. ```APIDOC { "apiName": "Brave Web Search API", "section": "Request Headers", "description": "This table lists the request headers supported by the Web Search API. Most are optional, but note that sending more information in headers (such as client location) will improve search results.", "headers": [ { "name": "Accept", "required": false, "description": "The default supported media type is `application/json`" }, { "name": "Accept-Encoding", "required": false, "description": "The supported compression type is `gzip`." }, { "name": "Api-Version", "required": false, "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)." }, { "name": "Cache-Control", "required": false, "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." }, { "name": "User-Agent", "required": false, "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/" }, { "name": "X-Loc-Lat", "required": false, "description": "The latitude of the client’s geographical location in degrees, to provide relevant local results. The latitiude must be greater than or equal to -90.0 degrees and less than or equal to +90.0 degrees." }, { "name": "X-Loc-Long", "required": false, "description": "The longitude of the client’s geographical location in degrees, to provide relevant local results. The longitude must be greater than or equal to -180.0 degrees and less than or equal to +180.0 degrees." }, { "name": "X-Loc-Timezone", "required": false, "description": "The IANA timezone for the client’s device, for example `America/New_York`. For complete list of IANA timezones and location mappings see [IANA Database](https://www.iana.org/time-zones) and [Geonames Database](https://download.geonames.org/export/dump/)." }, { "name": "X-Loc-City", "required": false, "description": "The generic name of the client city." }, { "name": "X-Loc-State", "required": false, "description": "The code representing the client’s state/region, can be up to 3 characters long. The region is the first-level subdivision (the broadest or least specific) of the [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) code." }, { "name": "X-Loc-State-Name", "required": false, "description": "The name of the client’s state/region. The region is the first-level subdivision (the broadest or least specific) of the [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) code." }, { "name": "X-Loc-Country", "required": false, "description": "The two letter code for the client’s country. For a list of country codes, see [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)" }, { "name": "X-Loc-Postal-Code", "required": false, "description": "The postal code of the client’s location." }, { "name": "X-Subscription-Token", "required": true, "description": "The secret token for the subscribed plan to authenticate the request. Can be obtained from [API Keys](/app/keys)." } ] } ``` -------------------------------- ### HTML: Image Search UI Structure Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/guides Defines the basic HTML structure for the image search interface. It includes an input field for queries, a search button, and a container for displaying image results. The JavaScript functions are linked via inline event handlers. ```html
``` -------------------------------- ### Perform Image Search with CURL and Brave API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/get-started This CURL command illustrates a basic GET request to the Brave Image Search API. It queries for 'munich' images, applies strict safe search, limits results to 20, and specifies English language and US country. Replace with your actual API subscription token for successful authentication. ```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 Search API: Request Header Versioning Example Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/general/api-versioning Illustrates how incremental, backwards-incompatible changes are managed using a dated 'Api-Version' header. This allows users to lock API behavior to a specific version, providing control over when to adopt new features or breaking changes. ```APIDOC Api-Version: 2023-01-01 ``` -------------------------------- ### Perform Spellcheck Query with CURL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/spellcheck/get-started This example demonstrates how to make a basic GET request to the Brave Spellcheck API using CURL. It includes essential headers for content negotiation and authentication, and queries for a misspelled word 'helo' in the US. ```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: " ``` -------------------------------- ### Perform Initial Web Search with Brave Summarizer API (cURL) Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search/get-started This cURL command demonstrates how to initiate a search query using the Brave Web Search API endpoint, specifically requesting a summary. This initial request is crucial as it provides the 'summarizer key' required for subsequent calls to retrieve the actual summarized content. ```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: " ``` -------------------------------- ### APIDOC: GET /api/images - Image Search Endpoint Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/guides Provides image search results based on a query. This endpoint is used by the frontend to retrieve image data for display. It supports a single query parameter 'q'. ```APIDOC { "endpoint": "/api/images", "method": "GET", "description": "Retrieves image search results.", "parameters": [ { "name": "q", "type": "string", "description": "The search query for images.", "required": true } ], "responses": { "200": { "description": "Successful retrieval of image results.", "schema": { "type": "object", "properties": { "results": { "type": "array", "items": { "type": "object", "properties": { "image": { "type": "object", "properties": { "title": { "type": "string", "description": "Title of the image." }, "thumbnail": { "type": "object", "properties": { "src": { "type": "string", "description": "URL of the image thumbnail." }, "width": { "type": "integer", "description": "Width of the thumbnail." }, "height": { "type": "integer", "description": "Height of the thumbnail." } } } } } } } } } } } } } ``` -------------------------------- ### Perform Initial Web Search with cURL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/get-started This cURL command demonstrates how to make an initial request to the Brave Web Search API with a given query. It accepts application/json and gzip encoding, requiring an X-Subscription-Token. The output is a list of search results, potentially including locations. ```curl curl -s --compressed "https://api.search.brave.com/res/v1/web/search?q=greek+restaurants+in+san+francisco" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### Create Node.js Express Server for Brave Image API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/guides This JavaScript code sets up an Express server to proxy requests to the Brave Search Image API. It handles GET requests to '/api/images', constructs API parameters, adds necessary headers including the API key, and returns the JSON response from the Brave API. This server-side approach is essential for preventing Cross-Origin Resource Sharing (CORS) issues when interacting with the API. ```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}`); }); ``` -------------------------------- ### Get Brave Local Search API POIs Endpoint URL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search This snippet provides the endpoint for the Brave Local Search API to retrieve Points of Interest (POIs). It allows for batching requests to get extra information for up to 20 locations in a single call. This endpoint is designed for enriching location-based search results. ```APIDOC https://api.search.brave.com/res/v1/local/pois ``` -------------------------------- ### Integrate Brave Search AI with OpenAI SDK in Python Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search This Python code snippet demonstrates how to use the OpenAI SDK to interact with Brave Search's AI summarizer endpoint. It requires the `openai` library and a Brave Search API key. The code sends a user query and prints the AI-generated response, which is derived from web context gathered by Brave Search. ```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) ``` -------------------------------- ### APIDOC: SummaryInlineReference Data Model Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search/responses Defines the structure for an inline reference within a summary message. It includes the type, URL, start and end indices, ordinal number, and optional favicon and snippet. ```APIDOC SummaryInlineReference { type: string (Required) - The type of inline reference. The value is always `inline_reference`. url: string (Required) - The URL that is being referenced. start_index: int (Required) - The start index of the inline reference in the summary message. end_index: int (Required) - The end index of the inline reference in the summary message. number: int (Required) - The ordinal number of the inline reference. favicon: string (Optional) - The favicon of the URL that is being referenced. snippet: string (Optional) - The reference text snippet. } ``` -------------------------------- ### Perform Initial Web Search with Brave Summarizer API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/summarizer-search Initiate a search query to the Brave Web Search API endpoint to check for summarization eligibility. This initial request is crucial for obtaining the summarizer key and is subject to billing based on your active subscription plan. ```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 Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/suggest/request-headers Detailed reference for all supported request headers for the Brave Suggest Search API. This includes information on their necessity, common names, and a full description of their function and expected values, such as media types, compression, API versioning, caching, user agent formats, and authentication tokens. ```APIDOC { "headers": [ { "header_name": "Accept", "required": false, "display_name": "Accept", "description": "The default supported media type is application/json" }, { "header_name": "Accept-Encoding", "required": false, "display_name": "Accept Encoding", "description": "The supported compression type is 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." }, { "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." }, { "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. 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_name": "X-Subscription-Token", "required": true, "display_name": "Authentication token", "description": "The secret token for the subscribed plan to authenticate the request. Can be obtained from API Keys." } ] } ``` -------------------------------- ### Implement Brave Search API Header Versioning Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/general For smaller, backwards incompatible changes, the API uses a dated version header Api-Version in YYYY-MM-DD format. Providing this header locks the API behavior to a specific version, allowing for controlled upgrades. ```APIDOC Api-Version: 2023-01-01 ``` -------------------------------- ### Perform Initial Web Search Query with cURL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/index This cURL command initiates a web search on the Brave API for a given query, expecting a JSON response. It requires an "X-Subscription-Token" (API key) for authentication and supports gzip compression. The output may contain location results with temporary IDs. ```curl curl -s --compressed "https://api.search.brave.com/res/v1/web/search?q=greek+restaurants+in+san+francisco" \ -H "Accept: application/json" \ -H "Accept-Encoding: gzip" \ -H "X-Subscription-Token: " ``` -------------------------------- ### JavaScript: Fetch Images from Brave API Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/image-search/guides Fetches image search results from the `/api/images` endpoint. It constructs a URL with the provided query parameter and returns the parsed JSON response. This function is asynchronous and relies on the browser's `fetch` API. ```javascript async function fetchImages(query) { const params = new URLSearchParams({ q: query }); const response = await fetch(`/api/images?${params}`); return await response.json(); return data; } ``` -------------------------------- ### Apply Brave Search API URL Versioning Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/general The Brave Search API uses a major version prefix like v1 in the request URL. This version is rarely updated and signifies a major API redesign, requiring a significant upgrade path for users. ```APIDOC /v1/web/search ``` -------------------------------- ### API Schema: Product Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/responses Represents a product model, detailing its name, category, price, and associated offers and ratings. It includes a thumbnail and an optional description. ```APIDOC class Product { type: "Product" (required) - A string representing a product type. The value is always `product`. name: string (required) - The name of the product. category: string (optional) - The category of the product. price: string (required) - The price of the product. thumbnail: Thumbnail (required) - A thumbnail associated with the product. description: string (optional) - The description of the product. offers: list (optional) - A list of offers available on the product. rating: Rating (optional) - A rating associated with the product. } ``` -------------------------------- ### API Schema: Offer Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/responses Defines an offer associated with a product, specifying the URL where the offer can be found, its price, and the currency. ```APIDOC class Offer { url: string (required) - The URL where the offer can be found. priceCurrency: string (required) - The currency in which the offer is made. price: string (required) - The price of the product currently on offer. } ``` -------------------------------- ### Get Brave Local Search API Descriptions Endpoint URL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search This snippet provides the endpoint for the Brave Local Search API to retrieve AI-generated descriptions for locations. It is part of the Local API offerings, providing additional contextual information. This endpoint enhances location data with descriptive summaries. ```APIDOC https://api.search.brave.com/res/v1/local/descriptions ``` -------------------------------- ### Get Brave Web Search API Endpoint URL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search This snippet provides the base URL for the Brave Web Search API. It is the primary endpoint for querying Brave Search and retrieving web search results in a JSON format. This URL forms the foundation for all web search API requests. ```APIDOC https://api.search.brave.com/res/v1/web/search ``` -------------------------------- ### Retrieve Brave Local Search API POIs Endpoint URL Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/get-started This snippet provides the base URL for the Brave Local Search API's Points of Interest (POIs) endpoint. It is used to get extra information about locations, supporting batch retrieval of up to 20 locations with a single request. ```APIDOC https://api.search.brave.com/res/v1/local/pois ``` -------------------------------- ### Local Search API Request Headers Reference Source: https://api-dashboard.search.brave.com/app/documentation/suggest/get-started/web-search/request-headers Documents the various request headers for the Local Search API, specifying their requirements, names, descriptions, and supported values or formats. It covers both optional and required headers for authenticating and controlling search behavior. ```APIDOC { "type": "API_REFERENCE", "name": "Local Search API Request Headers", "description": "Request headers supported by the Local Search API.", "headers": [ { "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)." } ] } ```