-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
501 lines (411 loc) Β· 14.5 KB
/
api.py
File metadata and controls
501 lines (411 loc) Β· 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
"""
Google Maps Scraper API
A lightweight FastAPI wrapper for Google Maps business data extraction.
Created by: dewhush
Endpoints:
- GET /health - Simple health check
- GET /status - Detailed service status
- POST /v1/scrape - Start scraping
- GET /v1/scrape/status - Get scraping progress
- POST /v1/scrape/stop - Stop current scrape
- GET /v1/results - Get scraping results
- DELETE /v1/results - Clear results
"""
import asyncio
import os
from datetime import datetime
from typing import Optional, List, Dict, Any
from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Import scraper
from scraper_async import AsyncGoogleMapsCrawler
# ===========================================
# Configuration
# ===========================================
API_KEY = os.getenv("API_KEY", "") # Set in .env
API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)
# ===========================================
# FastAPI App
# ===========================================
app = FastAPI(
title="Google Maps Scraper API",
description="Extract business leads from Google Maps. Created by dewhush.",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ===========================================
# Startup Banner
# ===========================================
@app.on_event("startup")
async def startup_event():
print("""
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GOOGLE MAPS SCRAPER API β
β Created by: dewhush β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββ£
β Docs: http://localhost:8000/docs β
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
# ===========================================
# Global State
# ===========================================
scraping_state = {
"is_running": False,
"progress": 0,
"total": 100,
"status": "idle",
"current_query": "",
"results_count": 0,
"started_at": None,
"error": None
}
results_storage: List[Dict[str, Any]] = []
active_crawler: Optional[AsyncGoogleMapsCrawler] = None
# ===========================================
# Request/Response Models
# ===========================================
class ScrapeRequest(BaseModel):
keyword: str
location: Optional[str] = None
limit: int = 20
headless: bool = True
phone_required: bool = True
website_required: bool = False
min_rating: float = 0.0
country_code: str = "ID"
class ScrapeStatus(BaseModel):
is_running: bool
progress: int
total: int
status: str
current_query: str
results_count: int
started_at: Optional[str]
error: Optional[str]
class BusinessLead(BaseModel):
name: str
phone: str
address: Optional[str]
website: Optional[str]
rating: Optional[str]
category: Optional[str]
lat: Optional[float]
lng: Optional[float]
# ===========================================
# Authentication
# ===========================================
async def verify_api_key(
api_key: Optional[str] = Depends(API_KEY_HEADER),
key: Optional[str] = Query(None, alias="api_key")
) -> bool:
"""Verify API key from header or query parameter"""
if not API_KEY:
return True
provided_key = api_key or key
if not provided_key or provided_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid or missing API key")
return True
# ===========================================
# Health & Status Endpoints
# ===========================================
@app.get("/health")
async def health_check():
"""Simple health check endpoint"""
return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}
@app.get("/status")
async def get_status():
"""Detailed service status"""
return {
"status": "online",
"service": "Google Maps Scraper API",
"version": "1.0.0",
"author": "dewhush",
"scraper_running": scraping_state["is_running"],
"timestamp": datetime.utcnow().isoformat()
}
# ===========================================
# Scraping Endpoints (v1)
# ===========================================
@app.post("/v1/scrape", dependencies=[Depends(verify_api_key)])
async def start_scraping(request: ScrapeRequest, background_tasks: BackgroundTasks):
"""
Start a new scraping job.
- **keyword**: Search keyword (e.g., "coffee shop")
- **location**: Location to search (e.g., "jakarta")
- **limit**: Maximum results to collect
"""
global active_crawler, scraping_state, results_storage
if scraping_state["is_running"]:
raise HTTPException(status_code=409, detail="Scraping already in progress")
# Build query from keyword + location
query = request.keyword
if request.location:
query = f"{request.keyword} {request.location}"
# Reset state
scraping_state.update({
"is_running": True,
"progress": 0,
"total": 100,
"status": "Starting...",
"current_query": query,
"results_count": 0,
"started_at": datetime.utcnow().isoformat(),
"error": None
})
results_storage = []
# Start scraping in background
background_tasks.add_task(run_scraper, request, query)
return {
"message": "Scraping started",
"query": query,
"limit": request.limit
}
async def run_scraper(request: ScrapeRequest, query: str):
"""Background task to run the scraper"""
global active_crawler, scraping_state, results_storage
try:
# Initialize crawler
config = {
"phone_required": request.phone_required,
"website_required": request.website_required,
"min_rating": request.min_rating,
"country_code": request.country_code,
"concurrency": 3
}
active_crawler = AsyncGoogleMapsCrawler(
headless=request.headless,
config=config
)
await active_crawler.setup_browser()
# Progress callback
async def update_progress(status: str, progress: int, total: int):
scraping_state.update({
"status": status,
"progress": progress,
"total": total,
"results_count": len(active_crawler.results)
})
# Run crawl
results = await active_crawler.crawl(
query=query,
max_results=request.limit,
progress_callback=update_progress
)
# Store results
results_storage = results
scraping_state.update({
"is_running": False,
"progress": 100,
"status": "Completed",
"results_count": len(results)
})
except Exception as e:
scraping_state.update({
"is_running": False,
"status": "Error",
"error": str(e)
})
finally:
if active_crawler:
await active_crawler.close()
active_crawler = None
@app.get("/v1/scrape/status", response_model=ScrapeStatus, dependencies=[Depends(verify_api_key)])
async def get_scraping_status():
"""Get current scraping progress"""
return ScrapeStatus(**scraping_state)
@app.post("/v1/scrape/stop", dependencies=[Depends(verify_api_key)])
async def stop_scraping():
"""Stop the current scraping job"""
global active_crawler, scraping_state
if not scraping_state["is_running"]:
raise HTTPException(status_code=400, detail="No scraping in progress")
try:
if active_crawler:
await active_crawler.close()
active_crawler = None
except:
pass
scraping_state.update({
"is_running": False,
"status": "Stopped by user"
})
return {"message": "Scraping stopped", "results_count": scraping_state["results_count"]}
# ===========================================
# Authentication (Mock/Compatibility)
# ===========================================
class LoginRequest(BaseModel):
email: str
password: str
class RegisterRequest(BaseModel):
name: str
email: str
password: str
otp: str
@app.post("/auth/login")
async def login(request: LoginRequest):
"""Mock login endpoint"""
return {
"access_token": "mock_token_12345",
"token_type": "bearer",
"user": {
"id": "user_1",
"name": "Demo User",
"email": request.email
}
}
@app.post("/auth/register")
async def register(request: RegisterRequest):
"""Mock register endpoint"""
return {
"access_token": "mock_token_12345",
"token_type": "bearer",
"user": {
"id": "user_1",
"name": request.name,
"email": request.email
}
}
@app.get("/auth/me")
async def get_me():
"""Mock user info endpoint"""
return {
"id": "user_1",
"name": "Demo User",
"email": "demo@example.com"
}
@app.post("/auth/send-otp")
async def send_otp(request: Dict[str, str]):
return {"message": "OTP sent"}
@app.post("/auth/verify-otp")
async def verify_otp(request: Dict[str, str]):
return {"message": "OTP verified"}
@app.post("/auth/forgot-password")
async def forgot_password(request: Dict[str, str]):
return {"message": "Password reset email sent"}
@app.post("/auth/reset-password")
async def reset_password(request: Dict[str, str]):
return {"message": "Password reset successfully"}
# ===========================================
# Dashboard & Stats (Compatibility)
# ===========================================
@app.get("/dashboard/stats")
async def get_dashboard_stats():
"""Mock dashboard stats"""
global results_storage
return {
"total_leads": len(results_storage),
"this_month": len(results_storage),
"total_exports": 0,
"last_activity": datetime.now().isoformat()
}
@app.get("/history")
async def get_history():
"""Mock history - currently mostly empty or static"""
return []
@app.get("/history/{history_id}")
async def get_history_details(history_id: str):
"""Mock history details - returns current results for demo"""
global results_storage
return results_storage
@app.delete("/history/{history_id}")
async def delete_history(history_id: str):
return {"message": "History deleted"}
# ===========================================
# Frontend Compatibility Wrappers
# ===========================================
@app.get("/contacts")
async def get_contacts_wrapper(history_id: Optional[str] = None):
"""Wrapper for /v1/results to match frontend expectation"""
global results_storage
return {
"contacts": results_storage,
"total": len(results_storage)
}
class FrontendScrapeRequest(BaseModel):
query: str
max_results: int = 50
headless: bool = True
phone_required: bool = True
website_required: bool = False
min_rating: float = 0.0
country_code: str = "ID"
min_reviews: int = 0
use_sub_areas: bool = False
@app.post("/scrape")
async def scrape_wrapper(request: FrontendScrapeRequest, background_tasks: BackgroundTasks):
"""Corrected wrapper handling frontend field names"""
# Convert to backend expected format
backend_req = ScrapeRequest(
keyword=request.query, # Mapping query to keyword
location="", # Frontend combines them usually
limit=request.max_results,
headless=request.headless,
phone_required=request.phone_required,
website_required=request.website_required,
min_rating=request.min_rating,
country_code=request.country_code
)
return await start_scraping(backend_req, background_tasks)
@app.get("/scrape/status")
async def scrape_status_wrapper():
"""Wrapper for /v1/scrape/status"""
return await get_scraping_status()
@app.post("/scrape/stop")
async def scrape_stop_wrapper():
"""Wrapper for /v1/scrape/stop"""
return await stop_scraping()
# End of Compatibility Layer
@app.get("/v1/results", dependencies=[Depends(verify_api_key)])
async def get_results(
limit: int = Query(100, description="Max results to return"),
offset: int = Query(0, description="Offset for pagination")
):
"""Get scraped results"""
global results_storage
total = len(results_storage)
data = results_storage[offset:offset + limit]
return {
"total": total,
"limit": limit,
"offset": offset,
"count": len(data),
"data": data
}
@app.delete("/v1/results", dependencies=[Depends(verify_api_key)])
async def clear_results():
"""Clear stored results"""
global results_storage
count = len(results_storage)
results_storage = []
return {"message": "Results cleared", "cleared_count": count}
# ===========================================
# Main Entry Point
# ===========================================
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", 8000))
print(f"""
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GOOGLE MAPS SCRAPER API β
β Created by: dewhush β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββ£
β Local: http://localhost:{port} β
β Docs: http://localhost:{port}/docs β
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
uvicorn.run("api:app", host="0.0.0.0", port=port, reload=True)