Ctrl K

Brave Search API

Validate and explore the Brave Search API from Python. This notebook covers authentication, a web search request use caase, and inspecting the structured response.

References

  • API docs: https://brave.com/search/api/
  • Dashboard: https://api-dashboard.search.brave.com/app/dashboard

Requirements

  • A Brave Search API key set in a .env file as BRAVE_API_KEY=your_key_here
  • pip install requests python-dotenv

Imports

In [3]:
import os
import json
import requests
from dotenv import load_dotenv

load_dotenv()

print("Imports OK")
Imports OK

Configuration

API key is read from .env. All search parameters are set here.

In [ ]:
BRAVE_API_KEY = os.getenv("BRAVE_API_KEY")

if not BRAVE_API_KEY:
    raise ValueError("BRAVE_API_KEY not found. Add it to a .env file as: BRAVE_API_KEY=your_key_here")

BASE_URL = "https://api.search.brave.com/res/v1/web/search"

QUERY       = "oil export controls"
COUNT       = 10          # number of results to return (max 20)
SEARCH_LANG = "en"
COUNTRY     = "us"

print(f"API key loaded : {'*' * 8}{BRAVE_API_KEY[-4:]}")
print(f"Query          : {QUERY}")
print(f"Count          : {COUNT}")
print(f"Language       : {SEARCH_LANG}")
print(f"Country        : {COUNTRY}")
API key loaded : ********k4wK
Query          : oil export controls
Count          : 10
Language       : en
Country        : us

Make the request

In [5]:
headers = {
    "Accept": "application/json",
    "Accept-Encoding": "gzip",
    "X-Subscription-Token": BRAVE_API_KEY,
}

params = {
    "q":           QUERY,
    "count":       COUNT,
    "search_lang": SEARCH_LANG,
    "country":     COUNTRY,
}

response = requests.get(BASE_URL, headers=headers, params=params, timeout=30)
response.raise_for_status()

data = response.json()

print(f"Status      : {response.status_code}")
print(f"Top-level keys: {list(data.keys())}")
Status      : 200
Top-level keys: ['type', 'query', 'mixed', 'videos', 'web']

Inspect the response structure

In [ ]:
query_meta = data.get("query", {})
print("Query metadata")
print("-" * 40)
for k, v in query_meta.items():
    print(f"  {k:<30} {v}")

print()
print("Result sections present:")
for key in ["web", "news", "videos", "images", "mixed"]:
    section = data.get(key)
    if section:
        count = len(section.get("results", []))
        print(f"  {key:<10} {count} result(s)")
Query metadata
----------------------------------------
  original                       oil export controls
  show_strict_warning            False
  is_navigational                False
  is_news_breaking               False
  spellcheck_off                 False
  country                        us
  bad_results                    False
  should_fallback                False
  postal_code                    
  city                           
  header_country                 
  more_results_available         True
  state                          

Result sections present:
  web        10 result(s)
  videos     5 result(s)
  mixed      0 result(s)

Web results preview

In [ ]:
web_results = data.get("web", {}).get("results", [])

print(f"Web results: {len(web_results)}")
print("=" * 60)

for i, result in enumerate(web_results, start=1):
    title       = result.get("title", "—")
    url         = result.get("url", "—")
    description = result.get("description", "—")
    age         = result.get("age", "")

    print(f"[{i}] {title}")
    print(f"    {url}")
    if age:
        print(f"    {age}")
    print(f"    {description[:160]}")
    print()
Web results: 10
============================================================
[1] U.S. Crude Oil Export Policy: Background and Considerations | Congress.gov | Library of Congress
    https://www.congress.gov/crs-product/R43442
    The export of domestically produced ... <strong>the Energy Policy and Conservation Act of 1975 (EPCA)23 and the resultant Short Supply Control Regulations adopt

[2] Why an Oil Export Ban Could Backfire on Fuel Prices
    https://www.investopedia.com/what-would-happen-if-the-us-stopped-exporting-oil-11933591
    3 weeks ago
    The idea of an export ban makes a certain kind of sense: by restricting oil companies from selling their products overseas, they’d have no choice but to sell to

[3] Trump officials rule out oil export ban in meeting with industry execs - POLITICO
    https://www.politico.com/news/2026/03/19/white-house-crude-export-ban-oil-iran-00836300
    1 month ago
    The White House has been searching for ways to reverse the steep climb in oil and gasoline prices that has resulted from Iranian attacks on oil and gas fields i

[4] Why Restricting US Oil Exports Would Backfire - Center on Global Energy Policy at Columbia University SIPA | CGEP %
    https://www.energypolicy.columbia.edu/why-restricting-us-oil-exports-would-backfire/
    1 day ago
    While legally feasible, export restrictions would likely backfire—offering limited relief to US consumers while imposing economic and geopolitical costs. The id

[5] Crude oil export ban - Ballotpedia
    https://ballotpedia.org/Crude_oil_export_ban
    At the time of the embargo, U.S. ... Congress passed the 1975 Energy Policy and Conservation Act, which directed the president to <strong>ban crude oil exports 

[6] Lifting the U.S. Crude Oil Export Ban
    https://www.kansascityfed.org/Economic%20Review/documents/468/Lifting_the_U.S._Crude_Oil_Export_Ban_Prospects_for_Increasing_Oil_Market_Efficiency06.pdf
    changed the U.S. oil market and gave rise to government controls on · imports, exports, and prices.

[7] White House Takes Crude Oil Export Ban Off the Table | SupplyChainBrain
    https://www.supplychainbrain.com/articles/43695-white-house-takes-crude-oil-export-ban-off-the-table
    1 month ago
    A crude oil tanker departs the Port of Corpus Christi in Corpus Christi, Texas. Photographer: Eddie Seal/Bloomberg ... The White House doesn’t plan to ban the e

[8] Breakingviews - US oil export ban: a bad idea whose time is coming
    https://www.reuters.com/commentary/breakingviews/us-oil-export-ban-a-bad-idea-whose-time-is-coming-2026-04-14/
    1 day ago
    More demand, however, will lead to higher prices. The easy populist ​answer is to <strong>stop 4 mln barrels ​of crude from leaving the country daily</strong>. 

[9] U.S. GAO - Crude Oil Markets: Effects of the Repeal of the Crude Oil Export Ban
    https://www.gao.gov/products/gao-21-118
    October 21, 2020
    Crude Oil, 2009-2019 · GAO&#x27;s analysis found limited effects associated with the repeal of the ban on the production, export, and import of domestic refined

[10] Is a US Oil Export Ban Coming? – Economist Writing Every Day
    https://economistwritingeveryday.com/2026/03/12/is-a-us-oil-export-ban-coming/
    March 12, 2026
    Only because US oil companies can sell to global markets, and they won’t choose to sell a barrel of oil to a US refiner for $60 when they could sell it to a for

In [ ]:
# print(json.dumps(data, indent=2, ensure_ascii=False))