{"record":{"id":"7af1e2064dd0f763","repo":"assafelovic/gpt-researcher","slug":"serpapi-api-key-not-found-please-set-the-serpapi","errorCode":null,"errorMessage":"SerpApi API key not found. Please set the SERPAPI_API_KEY environment variable. You can get a key at https://serpapi.com/","messagePattern":"SerpApi API key not found\\. Please set the SERPAPI_API_KEY environment variable\\. You can get a key at https://serpapi\\.com/","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"gpt_researcher/retrievers/serpapi/serpapi.py","lineNumber":32,"sourceCode":"        \"\"\"\n        Initializes the SerpApiSearch object\n        Args:\n            query:\n        \"\"\"\n        self.query = query\n        self.query_domains = query_domains or None\n        self.api_key = self.get_api_key()\n\n    def get_api_key(self):\n        \"\"\"\n        Gets the SerpApi API key\n        Returns:\n\n        \"\"\"\n        try:\n            api_key = os.environ[\"SERPAPI_API_KEY\"]\n        except Exception:\n            raise Exception(\"SerpApi API key not found. Please set the SERPAPI_API_KEY environment variable. \"\n                            \"You can get a key at https://serpapi.com/\")\n        return api_key\n\n    def search(self, max_results=7):\n        \"\"\"\n        Searches the query\n        Returns:\n\n        \"\"\"\n        print(\"SerpApiSearch: Searching with query {0}...\".format(self.query))\n        \"\"\"Useful for general internet search queries using SerpApi.\"\"\"\n\n        url = \"https://serpapi.com/search.json\"\n\n        search_query = self.query\n        if self.query_domains:\n            # Add site:domain1 OR site:domain2 OR ... to the search query\n            search_query += \" site:\" + \" OR site:\".join(self.query_domains)","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/assafelovic/gpt-researcher/blob/6f998577d547b1e54ec662dac63583aa11e3b84b/gpt_researcher/retrievers/serpapi/serpapi.py#L14-L50","documentation":"The SerpApi retriever requires an API key to authenticate with serpapi.com. During SerpApiRetriever construction, get_api_key() reads os.environ['SERPAPI_API_KEY'] and raises a plain Exception when the variable is absent. This is a configuration error that surfaces before any network call is made.","triggerScenarios":"Instantiating the SerpApi retriever (directly or via GPT Researcher's retriever registry with retrieval provider 'serpapi') in a process where the SERPAPI_API_KEY environment variable is not set (including unset, empty-string counts as set, but missing raises KeyError caught by the bare except).","commonSituations":"Running in a fresh shell/CI container without exporting the var; .env file not loaded because python-dotenv was never invoked; deploying to Docker/systemd where env vars from the local shell don't propagate; typos like SERP_API_KEY.","solutions":["Set the variable: export SERPAPI_API_KEY='your-key' (or add SERPAPI_API_KEY=... to .env and ensure it's loaded before constructing the retriever).","For Docker deployments, pass it with -e SERPAPI_API_KEY=... or in the compose environment section.","Get a valid key at https://serpapi.com if you don't have one.","Verify with python -c \"import os; print(os.environ.get('SERPAPI_API_KEY'))\" before running the app."],"exampleFix":"# before\nretriever = SerpApiRetriever(query='openai')  # raises: SerpApi API key not found\n\n# after\nimport os\nos.environ['SERPAPI_API_KEY'] = 'your-key'\nretriever = SerpApiRetriever(query='openai')","handlingStrategy":"validation","validationCode":"import os\n\nif not os.environ.get('SERPAPI_API_KEY'):\n    raise SystemExit('SERPAPI_API_KEY is not set — get a key at https://serpapi.com')","typeGuard":null,"tryCatchPattern":"try:\n    retriever = SerpApiRetriever(query='...')\nexcept Exception as e:\n    if 'API key not found' in str(e):\n        # config problem, not transient — fix env and restart\n        raise SystemExit(f'Config error: {e}')\n    raise","preventionTips":["Load .env with python-dotenv at process start, before any retriever import side effects.","Centralize API keys in a settings object validated at startup so misconfig fails fast.","In Docker/CI, add a container init check that all required *_API_KEY vars are present.","Use a secrets manager or platform secrets rather than ad-hoc exports."],"tags":["serpapi","api-key","environment-variable","configuration","retriever"],"backgroundTag":"missing-env-var","analyzedSha":"6f998577d547b1e54ec662dac63583aa11e3b84b","analyzedAt":"2026-08-28T17:50:07.383Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}