The script below exports every business a 2GIS search finds to a CSV with phones, websites, emails, rating, review count and coordinates. It runs one search call per 50 results and one place call per business. A search for fitness in Kazan gave 280 businesses in 286 calls, and 273 of them had a phone number.
Why search results have no phones
2GIS's Places API returns a company's contacts in items.contact_groups, and only on keys that have an extra permission for that field. Keys don't have it by default. If 2GIS has granted yours that permission, the official API is the direct route.
The search page on 2gis.ru doesn't load contacts either. A parser has to open each business to get its phones. That second call is where the time goes: 280 of the 286 calls in the Kazan export below were place calls.
What one call returns
We make ToolzerHub. Our 2GIS API has a search route that returns up to 50 businesses a page with ids, and a place route that returns one business with its contacts. Each call is a GET with the x-api-key header.
export TOOLZERHUB_API_KEY=your_key
curl -H "x-api-key: $TOOLZERHUB_API_KEY" \
"https://api.toolzerhub.com/v1/2gis/place?id=70000001060205718"
A Kazan fitness centre from that call, trimmed to the fields the script keeps:
{
"name": "Акимбо, фитнес-центр",
"primary_rubric": "Фитнес-клубы",
"rating": 4.8,
"review_count": 472,
"contacts": {
"phones": [{ "value": "+78432039381", "text": "+7 (843) 203‒93‒81" }],
"websites": [{ "value": "http://akimbofit.ru", "text": "akimbofit.ru" }],
"emails": [{ "value": "akimbofit@bk.ru", "text": "akimbofit@bk.ru" }]
},
"latitude": 55.78426,
"longitude": 49.234957,
"url": "https://2gis.ru/kazan/firm/70000001060205718"
}
The place response also has schedule, with opening hours per weekday, and org_review_count, which counts reviews across a chain's branches: 1,859 for this club's four. Add either to the row if you need it.
The search response carries total, which is 280 for this query, so you know how many pages to walk. Rows can repeat across pages, so the script skips ids it has already seen.
Export 2GIS businesses to CSV
The script takes a search query and a city slug, walks up to max_pages pages of 50, and calls place once per new business. Phones, websites and emails go into one cell each, joined with semicolons. The city is a slug such as kazan or almaty; /v1/2gis/cities lists all 206, with 154 in Russia and 19 in Kazakhstan.
import csv
import math
import os
import sys
import time
import requests
API = "https://api.toolzerhub.com/v1/2gis"
KEY = os.environ.get("TOOLZERHUB_API_KEY")
calls = 0
def cell(value):
# A leading = + - or @ would run as a formula when the CSV opens in a spreadsheet.
return "'" + value if isinstance(value, str) and value[:1] in ("=", "+", "-", "@") else value
def get(path, params, tries=4):
global calls
calls += 1
# 429 and 503 are worth a retry; the body says how long to wait.
for attempt in range(tries):
r = requests.get(f"{API}/{path}", params=params, headers={"x-api-key": KEY}, timeout=90)
if r.status_code in (429, 503) and attempt < tries - 1:
wait = int(((r.json().get("error") or {}).get("details") or {}).get("retryAfter") or r.headers.get("Retry-After") or 5 * (attempt + 1))
time.sleep(min(wait, 60))
continue
r.raise_for_status()
return r.json()["data"]
def search(query, city, max_pages):
first = get("search", {"query": query, "city": city, "page_size": 50})
yield from first["results"]
pages = min(math.ceil(first["total"] / 50), max_pages)
for page in range(2, pages + 1):
yield from get("search", {"query": query, "city": city, "page_size": 50, "page": page})["results"]
def joined(contacts, kind):
return "; ".join(c["text"] for c in contacts.get(kind) or [])
def main(query, city, max_pages="5", out="2gis.csv"):
seen, rows = set(), []
for place in search(query, city, int(max_pages)):
if place["id"] in seen:
continue
seen.add(place["id"])
detail = get("place", {"id": place["id"]}) or place
contacts = detail.get("contacts") or {}
rows.append({
"name": detail["name"],
"category": detail.get("primary_rubric"),
"address": (detail.get("address") or {}).get("street_address"),
"phones": joined(contacts, "phones"),
"websites": joined(contacts, "websites"),
"emails": joined(contacts, "emails"),
"rating": detail.get("rating"),
"reviews": detail.get("review_count"),
"latitude": detail.get("latitude"),
"longitude": detail.get("longitude"),
"url": detail.get("url"),
})
with open(out, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]) if rows else ["name"])
writer.writeheader()
writer.writerows({k: cell(v) for k, v in r.items()} for r in rows)
print(f"{len(rows)} businesses in {calls} calls, saved to {out}")
if __name__ == "__main__":
if not KEY or len(sys.argv) < 3:
sys.exit("usage: TOOLZERHUB_API_KEY=... python twogis_businesses.py QUERY CITY [max_pages] [file.csv]")
main(*sys.argv[1:])
What came out
python twogis_businesses.py фитнес kazan 10 kazan-fitness.csv saved 280 businesses in 286 calls and 219 seconds.
- 273 had a phone, 189 a website and 41 an email; 7 had none of the three. One business listed four phones. Phones are saved as 2GIS displays them, such as +7 (843) 203‒93‒81; change
texttovalueinjoinedfor digits only. - The 280 businesses had 24,753 reviews between them: 33.5 for the median business and 3,168 for the busiest. 260 were rated, at an average of 4.74.
- The search reached past gyms: 182 rows were fitness clubs, 23 dance schools, 23 gyms and 18 yoga studios. Filter on
categoryif you want one kind.
What it costs
A business costs 1 credit for its place call, plus 1 credit per 50-row search page, so 280 businesses took 286 credits. The 100 free credits a month cover about 98 businesses; $19 buys 10,000 credits that never expire, and plans for higher volume cover more cities. Set your key and your first city is a CSV in a few minutes.
To pull the written reviews of a business you found, see the 2GIS reviews API guide, and for the same job on Yandex Maps, the Yandex Maps parser in Python.
We are not affiliated with 2GIS.