문서 둘러보기
시작하기
Google Search 및 YouTube API를 HTTP에 직접 호출하십시오. 1개의 요구를 보내고 JSON 응답을 읽으십시오; SDK가 요구되지 않습니다.
인증현황
계정을 만들고 이메일을 확인하고 Google Search 권한으로 키를 만듭니다. 기존의 키를 재사용할 수 있습니다.
터미널에서 실행한 뒤 입력이 숨겨지는 프롬프트에 키를 붙여 넣으세요. FLASHDATA_API_KEY가 이미 설정되어 있다면 건너뛰세요.
키 설정# Bash: paste the key into a hidden prompt, not into this command. read -r -s -p "FlashData API key: " FLASHDATA_API_KEY printf '\n' export FLASHDATA_API_KEY키 설정# PowerShell 7: paste the key into a hidden prompt. $flashdataSecureKey = Read-Host "FlashData API key" -AsSecureString $env:FLASHDATA_API_KEY = [System.Net.NetworkCredential]::new("", $flashdataSecureKey).Password Remove-Variable flashdataSecureKey검색 실행
클라이언트를 선택하고 같은 터미널에서 예제를 실행하십시오. 각각은 https://data.flashdata.dev/v1/queries/realtime에 1개의 POST 요구를 보내고 JSON를 인쇄합니다. X-API-Key로 인증; JSON를 Content-Type로 보내: application/json.
cURL 7.76+ · Linux, macOS 또는 Git Bash에 Bash. 페이스 북과 실행.
검색 · Bash / cURLcurl --fail-with-body --silent --show-error --max-time 70 \ --request POST https://data.flashdata.dev/v1/queries/realtime \ --header "X-API-Key: $FLASHDATA_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "source": "google_search", "query": "battery recycling research", "params": { "num": 5 } }'PowerShell 7+ · 이 고유 PowerShell 명령을 붙여 넣으십시오.
검색 · PowerShell$flashdataRequest = '{"source":"google_search","query":"battery recycling research","params":{"num":5}}' $flashdataSearch = @{ Uri = 'https://data.flashdata.dev/v1/queries/realtime' Method = 'Post' Headers = @{ 'X-API-Key' = $env:FLASHDATA_API_KEY } ContentType = 'application/json' Body = $flashdataRequest TimeoutSec = 70 MaximumRedirection = 0 SkipHttpErrorCheck = $true ErrorAction = 'Stop' } $flashdataResponse = Invoke-WebRequest @flashdataSearch $flashdataResponse.Content if ($flashdataResponse.StatusCode -ge 400) { throw "HTTP $($flashdataResponse.StatusCode). Inspect the response above before retrying." }Node.js 22+ · search.mjs로 저장하고 로컬 또는 서버에서 실행하십시오. 내장된 fetch를 사용하십시오; npm 설치 없음.
search.mjsconst key = process.env.FLASHDATA_API_KEY; if (!key) throw new Error("Set FLASHDATA_API_KEY in this terminal."); let response; try { response = await fetch("https://data.flashdata.dev/v1/queries/realtime", { method: "POST", redirect: "error", signal: AbortSignal.timeout(70000), headers: { "X-API-Key": key, "Content-Type": "application/json" }, body: JSON.stringify({"source":"google_search","query":"battery recycling research","params":{"num":5}}), }); } catch { throw new Error("Request did not complete. Check History before resubmitting."); } const body = await response.text(); console.log(body); // Print the full response before checking its status. if (!response.ok) { const retryAfter = response.headers.get("retry-after"); throw new Error("HTTP " + response.status + ". See the response above." + (retryAfter ? " Retry-After: " + retryAfter : "")); } let result; try { result = JSON.parse(body); } catch { throw new Error("Expected JSON. Inspect the response above and the API URL."); } if (!result || result.error === true || result.status !== "done" || !Array.isArray(result.results)) { throw new Error("Query did not succeed. Inspect status and error in the response above."); }실행 · JavaScriptnode search.mjsPython 3.10+ · search.py로 저장하십시오. 표준 라이브러리 만 사용하십시오. pip 설치가 없습니다. python3 또는 py -3를 사용한다면 Python 명령입니다.
search.pyimport json import os import urllib.error import urllib.request key = os.environ.get("FLASHDATA_API_KEY") if not key: raise SystemExit("Set FLASHDATA_API_KEY in this terminal.") # Do not forward the API key to a redirect destination. class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None request = urllib.request.Request( "https://data.flashdata.dev/v1/queries/realtime", data=json.dumps({"source":"google_search","query":"battery recycling research","params":{"num":5}}).encode("utf-8"), headers={"X-API-Key": key, "Content-Type": "application/json"}, method="POST", ) try: with urllib.request.build_opener(NoRedirect).open(request, timeout=70) as response: body = response.read().decode("utf-8") except urllib.error.HTTPError as error: print(error.read().decode("utf-8", errors="replace")) retry_after = error.headers.get("Retry-After") raise SystemExit("HTTP " + str(error.code) + ". See the response above." + (" Retry-After: " + retry_after if retry_after else "")) except (urllib.error.URLError, TimeoutError): raise SystemExit("Request did not complete. Check History before resubmitting.") print(body) # The run command saves this full response to result.json. try: result = json.loads(body) except json.JSONDecodeError: raise SystemExit("Expected JSON. Inspect the response above and the API URL.") if (not isinstance(result, dict) or result.get("error") is True or result.get("status") != "done" or not isinstance(result.get("results"), list)): raise SystemExit("Query did not succeed. Inspect status and error in the response above.")실행 · Pythonpython -X utf8 search.py결과 확인
HTTP 성공 및 status: done를 확인하십시오. results[].organic의 소스 제목, 링크 및 스니펫을 읽고 usage.credits의 충전.
status: done를 가진 빈 결과 또는 유기 명부는 유효한 빈 결과입니다.
예시 응답{ "source": "google_search", "status": "done", "results": [ { "organic": [ { "title": "Battery recycling research", "link": "https://example.org/recycling", "snippet": "An example search excerpt." } ] } ], "usage": { "credits": 0.02 } }status- "done"는 성공적으로 완료된 쿼리를 확인합니다.
results[0].organic[]- 검색 결과. 그 결과가 색인하기 전에 비어있는 것을 확인합니다.
title / link / snippet- 소스 제목, URL 및 발췌.
usage.credits- 이 쿼리에 대해 청구 된 실제 크레딧.
디버깅에 대한 응답을 저장
다음 요청을 캡처하려면 위의 cURL 명령에 이러한 옵션을 추가하십시오. 실패한 요청을 재발행하기 전에 파일을 검사합니다.
--dump-header response-headers.txt --output result.json액세스 및 크레딧 확인
이 GET 요청은 쿼리 크레딧을 사용하지 않고 정체성, 균형 및 가격을 읽습니다. HTTP 200를 기대하고 유료 작업을 제출하기 전에 아래의 필드를 확인하십시오.
계정 읽기 : https://api.flashdata.dev/v2. 데이터 요청: https://data.flashdata.dev/v1. 둘 다 사용 X-API-Key; JSON POST는 또한 Content-Type를 사용합니다: application/json.
(
for endpoint in 'identity' 'balance' 'pricing?source=google_search&request_count=1'; do
printf '\n%s\n' "$endpoint"
curl --fail-with-body --silent --show-error --max-time 20 \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--write-out '\nHTTP %{http_code}\n' \
"https://api.flashdata.dev/v2/api-access/$endpoint" || exit
done
)try {
foreach ($flashdataPath in @('identity', 'balance', 'pricing?source=google_search&request_count=1')) {
Write-Host $flashdataPath
$flashdataRead = @{
Uri = "https://api.flashdata.dev/v2/api-access/$flashdataPath"
Headers = @{ 'X-API-Key' = $env:FLASHDATA_API_KEY }
TimeoutSec = 20
MaximumRedirection = 0
ErrorAction = 'Stop'
}
Invoke-RestMethod @flashdataRead | ConvertTo-Json -Depth 20
}
} catch {
throw
}identity- 자주 묻는 질문 accountId, access: "ready", 포함되는 범위 "google_search", 그리고 어떤 expiresAt. accountType 는 "owned" 소유자 키 또는 "temporary" 시험 열쇠를 위해.
balance- availableCredits를 읽으십시오. 이 계정의 모든 키는 동일한 균형을 사용합니다.
pricing- 가격[0]의 경우, 소스는 google_search이며 true입니다. requestCount에 대한 estimatedCredits 비교: availableCredits와 1. 가격 및 균형은 제출하기 전에 변경할 수 있습니다.
다음 단계
단계가 실패한 경우
당신의 맨끝에서 인쇄된 응답을 읽으십시오. JavaScript 및 Python 보고서 HTTP 오류 및 Retry-After에 stderr. 각 예제는 한 번 제출합니다. 자동으로 재발하지 않습니다.
- 명령 누락되거나 지원되지 않은 옵션
- 선택된 예에서 필수 버전을 확인. 제품 정보 PowerShell 7 더 많은 것 Windows PowerShell 5.1, 또는 사용 Bash 으로 cURL 7.76+. JavaScript는 Node 22+를 필요로 합니다; Python는 3.10+를 필요로 합니다. 공식 다운로드 페이지에서 누락된 실행 시간을 설치하고, 터미널을 다시 엽니다.
- 열쇠/401를 끄기
- 이 과정에서 FLASHDATA_API_KEY를 설정하고 ID를 다시 확인하십시오. Bearer 접두사 없이 가득 차있는 활동적인 API 열쇠를 공급하십시오. 만료되거나 수정 된 경우, 현재 공인 자격 증명을 사용하십시오. 채팅으로 붙여 넣지 마십시오.
- 403
- google_search에 identity.scopes를 확인하고 준비할 수 있습니다. 소유자의 누락 된 권한을 요청하십시오. 요청에 소스를 변경하면 액세스 권한을 부여하지 않습니다.
- 402
- 잔액을 다시 읽고 현재 가격을 비교하십시오. 소유자는 Billing를 검토 할 수 있습니다. 소진된 시험은 주장을 통해 소유자 접근을 필요로 합니다; 보충 예심을 창조하는 것은 회복이 아닙니다.
- 400 / 422
- 반환된 오류 메시지를 읽으십시오. 정확한 데이터 호스트를 확인, POST 방법, Content-Type 및 JSON 필드 이름. 스트레이트 따옴표와 숫자 params.num를 사용하여, 다음 거부된 요청을 수정합니다.
- 429
- 현재 Retry-After를 재경로; 그렇지 않으면 경계를 끄고 concurrency를 감소시킵니다. 신속하게 반복하지 않고 새로운 키를 만들거나 제한을 우회하기 위해 다른 체험을 등록하십시오.
- 실패 상태 또는 오류가있는 HTTP 200
- 신체의 오류를 읽고 어떤 요청 또는 작업 ID를 보존하십시오. 성공적인 작업으로 JSON 본체를 파쇄하지 마십시오.
- 빈 결과
- 상태가 완료되면 인증이 일했습니다. 빈 결과를 유지하거나 새로운 유료 요청으로 더 넓은 쿼리를 시도하십시오.
- JSON 대신에 Timeout, 연결 손실, 5xx 또는 HTML
- POST는 응답이 잃어버린 경우에도 허용 될 수있다. 원래 쿼리에 History를 확인하고 resend를 결정하기 전에 반환 IDs를 보존하십시오. 무료 GET 체크인은 검색 할 수 있습니다. URL는 웹 사이트 호스트가 아닌 data.flashdata.dev를 사용하고 TLS 검증을 사용하지 않습니다.