# Use Facebook Marketplace Search API with Python

SocialScraper Engineering · 2026-11-28

Find Facebook Marketplace listings by keyword and coordinates for local product research.

Use these Facebook records for product discovery and commerce research. Link selected products to their detail records before comparing listings or preparing a creator-commerce report.

## Before you begin

Use Python 3.10 or newer, a terminal and a customer API key. The script uses urllib, json and pathlib from the standard library. Save the Python file and its JSON input file in the same directory.

## Configure your API key

Replace YOUR_API_KEY privately with your customer key. Keep the variable in the environment used by the script; the source code reads it without storing the key in the file.

```sh
export SOCIALSCRAPER_API_KEY="YOUR_API_KEY"
```

## Prepare the endpoint inputs

`GET /v1/facebook/marketplace_search`

```json
{
  "lat": 30.2677,
  "lng": -97.7475
}
```

### query

string · Optional

Search text used to find matching public content.



### lat

number · Required

Latitude of the search location in decimal degrees.



### lng

number · Required

Longitude of the search location in decimal degrees.



### category_id

string · Optional

Category identifier used by facebook. Send the identifier as text to preserve its full value.



### radius_km

number · Optional

Search radius around the selected location, in kilometres.



### min_price

number · Optional

Lower price boundary for product listings.



### max_price

number · Optional

Upper price boundary for product listings.



### sort_by

string · Optional

Ordering of returned results. Choose one of the allowed sort modes below.

Allowed values: "suggested", "distance_ascend", "creation_time_descend", "price_ascend", "price_descend"

### delivery_method

string · Optional

Delivery or fulfilment method for marketplace listings.

Allowed values: "all", "local_pickup", "shipping"

### condition

string · Optional

Item condition filter for marketplace listings.

Allowed values: "new", "used_like_new", "used_good", "used_fair"

### date_listed

string · Optional

Publication date or time-window filter for matching content.

Allowed values: "all", "1", "7", "30", "last_24_hours", "last_7_days", "last_30_days"

### availability

string · Optional

Status filter for the matching records.

Allowed values: "available", "sold", "all"

### cursor

string · Optional

Continuation value from the preceding response. Keep the other search or target parameters unchanged when loading the next page.



## Complete implementation

```python
#!/usr/bin/env python3
"""Facebook Marketplace Search API: GET /v1/facebook/marketplace_search"""
import argparse
import json
import os
import uuid
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

DEFAULT_INPUT = json.loads("{\"lat\":30.2677,\"lng\":-97.7475}")
parser = argparse.ArgumentParser(description="Facebook Marketplace Search API")
parser.add_argument("--input", type=Path, help="JSON file containing endpoint inputs")
parser.add_argument("--request-key", help="Original key for one identical retry")
parser.add_argument("--output", type=Path, default=Path("result.json"))
parser.add_argument("--pages", type=int, default=1, help="Maximum number of pages, 1 to 20")
args = parser.parse_args()
if not 1 <= args.pages <= 20:
    parser.error("--pages must be between 1 and 20")
if args.request_key and args.pages != 1:
    parser.error("--request-key requires --pages 1")
key = os.environ["SOCIALSCRAPER_API_KEY"]
base = os.environ.get("SOCIALSCRAPER_BASE_URL", "https://socialmediascraper.org").rstrip("/")
inputs = json.loads(args.input.read_text(encoding="utf-8")) if args.input else DEFAULT_INPUT.copy()
if not isinstance(inputs, dict):
    parser.error("--input must contain a JSON object")
responses = []
for page in range(args.pages):
    request_key = args.request_key or str(uuid.uuid4())
    headers = {"x-api-key": key, "Idempotency-Key": request_key}
    query = {name: (str(value).lower() if isinstance(value, bool) else value)
             for name, value in inputs.items()}
    request = Request(base + "/v1/facebook/marketplace_search" + "?" + urlencode(query), headers=headers)
    try:
        with urlopen(request, timeout=45) as response:
            result = json.load(response)
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        retry_after = error.headers.get("Retry-After", "")
        raise RuntimeError(f"HTTP {error.code}; request key={request_key}; Retry-After={retry_after}; {detail}") from error
    except (URLError, TimeoutError) as error:
        raise RuntimeError(f"Uncertain request outcome; retain request key={request_key}; {error}") from error
    responses.append(result)
    args.output.write_text(json.dumps({"operation": "facebook.marketplace_search", "requests": responses},
                                     ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"page": page + 1, "request_id": result["request_id"]}))
    cursor = result["data"].get("cursor")
    if cursor is None or cursor == "":
        break
    inputs = {**inputs, "cursor": cursor}
print(f"Saved {len(responses)} request response(s) to {args.output}")

```

## Run the script

```sh
python3 facebook.marketplace_search.py --input facebook.marketplace_search.input.json --output result.json --pages 1
```

## Read and use the result

The saved file has an operation label and a requests array. Each requests entry contains the original request_id, data and meta envelope. The JSON below shows one response; use the field table to choose what your application stores.

```json
{
  "request_id": "example-request-id",
  "data": {
    "platform": "facebook",
    "resource": "marketplace_search",
    "items": [
      {
        "id": "123456789",
        "position": 0,
        "url": "https://example.com/public-content",
        "title": "Example public content",
        "text": "Example public content",
        "published_at": null,
        "author": {
          "id": "123456789",
          "handle": "example",
          "display_name": "Example creator"
        },
        "metrics": {
          "views": null,
          "likes": 12,
          "comments": null,
          "shares": null
        },
        "price": {
          "amount": null,
          "formatted": null
        },
        "location": {
          "city": null,
          "state": null,
          "display_name": null
        },
        "is_sold": null
      }
    ],
    "cursor": null
  },
  "meta": {
    "platform": "facebook",
    "fetched_at": "2026-11-28T00:00:00.000Z",
    "cached": false,
    "schema_version": "2026-11-23.2",
    "route_version": 1,
    "billing": {
      "capability": "facebook.marketplace_search",
      "version": "2026-11-23.retail-1",
      "currency": "USD",
      "unit_scale": 1000000000,
      "amount_units": 2444000,
      "amount_usd": "0.002444000",
      "billing_basis": "request"
    }
  }
}
```

- `data.platform`: Source platform identifier.

- `data.resource`: Operation resource identifier.

- `data.items`: Records in the returned page or bounded result set.

- `data.items[].id`: Source identity preserved as text.

- `data.items[].position`: Zero-based position within this returned set.

- `data.items[].url`: Public source URL for this record.

- `data.items[].title`: Title or display label associated with the record.

- `data.items[].text`: Content text, biography or transcript text associated with this record.

- `data.items[].published_at`: Publication value supplied by the source.

- `data.items[].author`: Identity fields for the author or account represented by the record.

- `data.items[].author.id`: Source identity preserved as text.

- `data.items[].author.handle`: Public account username or handle.

- `data.items[].author.display_name`: Account or creator display name.

- `data.items[].metrics`: Available source metrics grouped by measurement.

- `data.items[].metrics.views`: Source-reported views measurement when present.

- `data.items[].metrics.likes`: Source-reported likes measurement when present.

- `data.items[].metrics.comments`: Source-reported comments measurement when present.

- `data.items[].metrics.shares`: Source-reported shares measurement when present.

- `data.items[].price`: Price fields returned for the product or listing.

- `data.items[].price.amount`: Numeric price amount associated with the returned price record.

- `data.items[].price.formatted`: Human-readable presentation of the associated value.

- `data.items[].location`: Source location fields associated with the record.

- `data.items[].location.city`: City value associated with this location.

- `data.items[].location.state`: State or region value associated with the location.

- `data.items[].location.display_name`: Account or creator display name.

- `data.items[].is_sold`: Sold-state flag for the listing.

- `data.cursor`: Continuation value for the next request; preserve its returned representation.

## Plan requests and pagination

Continue with the returned data.cursor and the documented input field: cursor. Keep the original target and filters. Each additional page is a new request with a new Idempotency-Key.

A new page is a new logical request. If the same request must be retried, keep its original Idempotency-Key and identical inputs. When the outcome is uncertain, query GET /v1/requests/:id before starting a replacement. The examples stop on an error rather than silently creating another request.

Published request price: $0.002444 USD. Each additional page is a separate request.

## Troubleshooting

400: Review the target URL, parameter types and identifier-combination rules.

401: Check SOCIALSCRAPER_API_KEY and the x-api-key header.

402: Check your USD balance and the selected operation’s price.

429: Read Retry-After and your current limits before retrying the same request.

[Open endpoint reference](https://socialmediascraper.org/apis/facebook/marketplace_search/)

[Python](https://socialmediascraper.org/tutorial-code/python/facebook.marketplace_search.py)
