> ## Documentation Index
> Fetch the complete documentation index at: https://docs.geekflare.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Use Geekflare API in any Python project with the official SDK or the requests library.

The official `geekflare-api` SDK provides a Pythonic interface that handles auth and serialization. Raw `requests` examples are included for those who prefer no extra dependencies.

## Prerequisites

* Python **3.8+**
* `pip` or `uv`
* A Geekflare API key — [get one free](https://dash.geekflare.com)

## Installation

<Tabs>
  <Tab title="pip">`bash pip install geekflare-api `</Tab>
  <Tab title="uv">`bash uv add geekflare-api `</Tab>

  <Tab title="pip + requests (no SDK)">
    `bash pip install requests python-dotenv `
  </Tab>
</Tabs>

## Set your API key

Create a `.env` file:

```bash .env theme={null}
GEEKFLARE_API_KEY=your_api_key_here
```

Load it in your script:

```python theme={null}
from dotenv import load_dotenv
import os

load_dotenv()
API_KEY = os.environ["GEEKFLARE_API_KEY"]
```

<Warning>Never hardcode your API key. Add `.env` to `.gitignore`.</Warning>

## Initialize the client

```python theme={null}
from geekflare_api.client import GeekflareClient

client = GeekflareClient(api_key=os.environ["GEEKFLARE_API_KEY"])
```

The client is a context manager — use `with` to ensure the underlying HTTP session is closed:

```python theme={null}
with GeekflareClient(api_key=os.environ["GEEKFLARE_API_KEY"]) as client:
    # make calls here
    pass
```

***

## Web Scraping

<Tabs>
  <Tab title="SDK">
    ```python theme={null}
    import os
    from dotenv import load_dotenv
    from geekflare_api.client import GeekflareClient
    from geekflare_api.models import WebScrapeDto

    load_dotenv()

    with GeekflareClient(api_key=os.environ["GEEKFLARE_API_KEY"]) as client:
        result = client.web_scrape(
            WebScrapeDto(
                url="https://toscrape.com/",
                renderJS=True,
                blockAds=True,
                format="html,markdown",
                device="desktop",
            )
        )
        print(result)
    ```
  </Tab>

  <Tab title="requests">
    ```python theme={null}
    import os
    import requests
    from dotenv import load_dotenv

    load_dotenv()

    response = requests.post(
        "https://api.geekflare.com/webscraping",
        headers={
            "Content-Type": "application/json",
            "x-api-key": os.environ["GEEKFLARE_API_KEY"],
        },
        json={
            "url": "https://toscrape.com/",
            "renderJS": True,
            "blockAds": True,
            "format": "html,markdown",
            "device": "desktop",
        },
    )

    response.raise_for_status()
    print(response.json())
    ```
  </Tab>
</Tabs>

**Key parameters:**

| Parameter      | Type    | Description                         |
| -------------- | ------- | ----------------------------------- |
| `url`          | `str`   | **Required.** The URL to scrape     |
| `renderJS`     | `bool`  | Wait for JavaScript to execute      |
| `blockAds`     | `bool`  | Block ads before scraping           |
| `format`       | `str`   | Comma-separated: `html`, `markdown` |
| `device`       | `str`   | `"desktop"` or `"mobile"`           |
| `proxyCountry` | `str`   | Route via country code, e.g. `"us"` |
| `stealth`      | `bool`  | Enable stealth mode                 |
| `waitTime`     | `float` | Extra wait time in seconds          |

**Example response:**

```json theme={null}
{
  "timestamp": 1779703261268,
  "apiStatus": "success",
  "apiCode": 200,
  "meta": {
    "url": "https://toscrape.com/",
    "device": "desktop",
    "format": ["html-llm"],
    "blockAds": true,
    "renderJS": true,
    "test": { "id": "mxqx9v9y0742lap6altwdteqd28t23nq" }
  },
  "data": "https://example.com/9bulgk075ed9m3vhua5vcrp0.html"
}
```

The `data` field is a URL to the scraped output file. See the [Web Scraping endpoint reference](https://docs.geekflare.com/api/endpoint/webscraping).

***

## Search

<Tabs>
  <Tab title="SDK">
    ```python theme={null}
    import os
    from dotenv import load_dotenv
    from geekflare_api.client import GeekflareClient
    from geekflare_api.models import SearchDto

    load_dotenv()

    with GeekflareClient(api_key=os.environ["GEEKFLARE_API_KEY"]) as client:
        result = client.search(
            SearchDto(
                query="best Python web frameworks",
                limit=10,
                location="us",
                source="web",
                time="m",
                format="json",
            )
        )
        print(result)
    ```
  </Tab>

  <Tab title="requests">
    ```python theme={null}
    import os
    import requests
    from dotenv import load_dotenv

    load_dotenv()

    response = requests.post(
        "https://api.geekflare.com/search",
        headers={
            "Content-Type": "application/json",
            "x-api-key": os.environ["GEEKFLARE_API_KEY"],
        },
        json={
            "query": "best Python web frameworks",
            "limit": 10,
            "location": "us",
            "source": "web",
            "time": "m",
            "format": "json",
        },
    )

    response.raise_for_status()
    data = response.json()

    for item in data.get("data", []):
        print(f"{item['title']} — {item['url']}")
        print(item['snippet'])
    ```
  </Tab>
</Tabs>

**Key parameters:**

| Parameter        | Type        | Description                                              |
| ---------------- | ----------- | -------------------------------------------------------- |
| `query`          | `str`       | **Required.** The search query                           |
| `limit`          | `int`       | Number of results (default: `10`)                        |
| `location`       | `str`       | Country code for localized results, e.g. `"us"`          |
| `source`         | `str`       | `"web"`, `"news"`, etc.                                  |
| `time`           | `str`       | Recency filter: `"d"` (day), `"w"` (week), `"m"` (month) |
| `includeDomains` | `list[str]` | Only return results from these domains                   |
| `excludeDomains` | `list[str]` | Exclude results from these domains                       |

***

## Screenshot

<Tabs>
  <Tab title="SDK">
    ```python theme={null}
    import os
    from dotenv import load_dotenv
    from geekflare_api.client import GeekflareClient
    from geekflare_api.models import ScreenshotDto

    load_dotenv()

    with GeekflareClient(api_key=os.environ["GEEKFLARE_API_KEY"]) as client:
        result = client.screenshot(
            ScreenshotDto(
                url="https://example.com",
                type="png",
                fullPage=True,
                device="desktop",
                viewportWidth=1280,
                viewportHeight=800,
                blockAds=True,
                hideCookie=True,
                quality=90,
            )
        )
        print(result)
    ```
  </Tab>

  <Tab title="requests">
    ```python theme={null}
    import os
    import requests
    from dotenv import load_dotenv

    load_dotenv()

    response = requests.post(
        "https://api.geekflare.com/screenshot",
        headers={
            "Content-Type": "application/json",
            "x-api-key": os.environ["GEEKFLARE_API_KEY"],
        },
        json={
            "url": "https://example.com",
            "type": "png",
            "fullPage": True,
            "device": "desktop",
            "viewportWidth": 1280,
            "viewportHeight": 800,
            "blockAds": True,
            "hideCookie": True,
            "quality": 90,
        },
    )

    response.raise_for_status()
    data = response.json()
    # data['data'] is the screenshot URL directly
    print("Screenshot URL:", data["data"])
    ```
  </Tab>
</Tabs>

***

## Error handling

<Tabs>
  <Tab title="SDK">
    ```python theme={null}
    import os
    from dotenv import load_dotenv
    from geekflare_api.client import GeekflareClient
    from geekflare_api.models import WebScrapeDto
    from geekflare_api.exceptions import ApiException

    load_dotenv()

    try:
        with GeekflareClient(api_key=os.environ["GEEKFLARE_API_KEY"]) as client:
            result = client.web_scrape(WebScrapeDto(url="https://toscrape.com/"))
            print(result)

    except ApiException as e:
        print(f"API error {e.status}: {e.reason}")

        if e.status == 401:
            print("Invalid or missing API key.")
        elif e.status == 402:
            print("API credits exhausted. Top up at dash.geekflare.com.")
        elif e.status == 403:
            print("This endpoint is not available on your current plan.")
        elif e.status == 429:
            print("Rate limit exceeded. Back off and retry.")

    except Exception as e:
        print(f"Unexpected error: {e}")
    ```
  </Tab>

  <Tab title="requests">
    ```python theme={null}
    import os
    import requests
    from dotenv import load_dotenv

    load_dotenv()

    try:
        response = requests.post(
            "https://api.geekflare.com/webscraping",
            headers={
                "Content-Type": "application/json",
                "x-api-key": os.environ["GEEKFLARE_API_KEY"],
            },
            json={"url": "https://toscrape.com/"},
        )
        response.raise_for_status()
        print(response.json())

    except requests.HTTPError as e:
        code = e.response.status_code
        body = e.response.json()

        if code == 401:
            print("Invalid or missing API key.")
        elif code == 402:
            print("API credits exhausted.")
        elif code == 403:
            print("Endpoint not available on your plan.")
        elif code == 429:
            print("Rate limit exceeded. Back off and retry.")
        else:
            print(f"HTTP {code}: {body.get('message', 'Unknown error')}")

    except requests.ConnectionError:
        print("Network error. Check your internet connection.")
    ```
  </Tab>
</Tabs>

### Common error codes

| Code  | Meaning                           |
| ----- | --------------------------------- |
| `401` | Missing or invalid `x-api-key`    |
| `402` | API credits exhausted             |
| `403` | Endpoint requires a higher plan   |
| `404` | Wrong endpoint URL or HTTP method |
| `429` | Rate limit exceeded               |

***

## Next steps

* [Django quickstart](/api/quickstart/django) — Views, services, and `python-decouple`
* [API Reference](/api/endpoint/reference) — Full endpoint documentation
* [SDK on PyPI](https://pypi.org/project/geekflare-api/)
