# Avvio rapido API

Chiama le API Google e YouTube direttamente sopra HTTP. Inviare una richiesta e leggere la risposta JSON; non è richiesto alcun SDK.

Riferimento canonico: https://flashdata.dev/it/docs/guides/http-quickstart
Recensito: 2026-11-04 da FlashData

<a id="application"></a>

## Fai la tua prima richiesta HTTP

Impostare il tasto API, inviare una ricerca Google e ispezionare la risposta salvata.


<a id="prepare"></a>

### Autentico

Crea un account, verifica la tua e-mail e crea una chiave con il permesso di ricerca Google. È possibile riutilizzare una chiave esistente.

Esegui il comando nel terminale e incolla la chiave nel campo nascosto. Salta questo passaggio se FLASHDATA_API_KEY è già impostata.

#### Bash

##### Imposta la chiave

```bash
# 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

##### Imposta la chiave

```powershell
# 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
```


- [Creare un account](https://flashdata.dev/signup)
- [Aprire API Keys](https://flashdata.dev/app/api-keys)
- [Autenticazione agente](https://flashdata.dev/auth.md)

<a id="curl"></a>

### Esegui una ricerca

Scegliere un client e eseguire l'esempio nello stesso terminale. Ciascuno invia una richiesta POST a https://data.flashdata.dev/v1/queries/realtime e stampa JSON. Autenticare con X-API-Key; inviare JSON con Content-Type: application/json.

#### cURL

cURL 7.76+ · Bash su Linux, macOS o Git Bash. Incolla e scappa.

##### Ricerca · Bash / cURL

```bash
curl --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 7+ · Incolla questo comando nativo PowerShell.

##### Ricerca · 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."
}
```


#### JavaScript

Node.js 22+ · Salvare come search.mjs ed eseguire localmente o sul server. Utilizza fetch incorporato; nessuna installazione npm.

##### search.mjs

```javascript
const 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.");
}
```

##### Correre · JavaScript

```bash
node search.mjs
```


#### Python

Python 3.10+ · Salva come search.py. Utilizza solo la libreria standard; nessun installazione pip. Utilizzare python3 o py -3 se questo è il vostro comando Python.

##### search.py

```python
import 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.")
```

##### Correre · Python

```bash
python -X utf8 search.py
```



<a id="result"></a>

### Verifica il risultato

Conferma il successo HTTP e status: done. Leggere i titoli, i link e i frammenti di origine in results[].organic, e l'addebito in usage.credits.

Un risultato vuoto o un elenco organico con status: done è un risultato vuoto valido.

| Campo di applicazione | Usalo per |
| --- | --- |
| status | "done" conferma la query completata con successo. |
| results[0].organic[] | Risultati di ricerca. Controllare che i risultati non sono inutili prima di indicizzarlo. |
| title / link / snippet | Titolo di origine, URL ed estratto. |
| usage.credits | Crediti effettivi addebitati per questa domanda. |

#### Esempio

```json
{
  "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
  }
}
```


<a id="diagnostics"></a>

## Salvare una risposta per il debug

Per catturare la successiva richiesta prevista, aggiungere queste opzioni al comando cURL sopra. Ispezionare i file prima di decidere di riprovare una richiesta fallita.

### cURL

```bash
--dump-header response-headers.txt --output result.json
```

- [Errori e ripristino HTTP](https://flashdata.dev/it/docs/errors/reference.md)

<a id="check"></a>

## Controllare l'accesso e i crediti

Queste richieste GET leggono identità, equilibrio e prezzi senza utilizzare crediti di query. Aspettatevi HTTP 200 e controlla i campi sottostanti prima di inviare il lavoro pagato.

L'account legge: https://api.flashdata.dev/v2. Richieste di dati: https://data.flashdata.dev/v1. Entrambi usano X-API-Key; Le richieste JSON POST utilizzano anche Content-Type: application/json.

| Leggi tutto | Cosa controllare nella risposta |
| --- | --- |
| identity | Confermare gli obiettivi accountId, access: "ready", gli ambiti contenenti "google_search", e qualsiasi expiresAt. accountType è "owned" per una chiave di prova o "temporary" per una chiave di prova. |
| balance | Leggi availableCredits. Tutte le chiavi di questo account utilizzano lo stesso equilibrio. |
| pricing | Per i prezzi[0], la fonte di conferma è google_search e disponibile è true. Confronta estimatedCredits per requestCount: 1 con availableCredits. I prezzi e gli saldi possono cambiare prima della presentazione. |

### Bash / cURL

#### Controlli gratuiti · Bash

```bash
(
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
)
```


### PowerShell 7

#### Controlli gratuiti · PowerShell

```powershell
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
}
```



<a id="next"></a>

## Prossimo passo

- [Google Cerca le migliori pratiche](https://flashdata.dev/it/docs/guides/google-search-guide/reference.md)
- [YouTube Data](https://flashdata.dev/it/docs/guides/youtube-data-guide/reference.md)
- [YouTube Download](https://flashdata.dev/it/docs/guides/youtube-download-guide/reference.md)
- [Riferimento API](https://flashdata.dev/it/docs/api-reference/reference.md)
- [Specificazione OpenAPI](https://flashdata.dev/docs/openapi.json)

<a id="troubleshooting"></a>

## Se un passo fallisce

Leggi la risposta stampata nel tuo terminale. Gli errori JavaScript e Python riportano gli errori HTTP e Retry-After a stderr. Ogni esempio si presenta una volta; non si riprova automaticamente.

| Sintomo | Prossima azione |
| --- | --- |
| Comando opzione mancante o non supportato | Controllare la versione richiesta nell'esempio selezionato. Utilizzare PowerShell 7 piuttosto che Windows PowerShell 5.1, o utilizzare Bash con cURL 7.76+. JavaScript ha bisogno di Node 22+; Python ha bisogno di 3.10+. Installare il runtime mancante dalla sua pagina di download ufficiale, riaprire il terminale, quindi impostare nuovamente la chiave. |
| Chiave mancante / 401 | Impostare FLASHDATA_API_KEY in questo processo e controllare nuovamente l'identità. Fornire il tasto API attivo completo, senza un prefisso Bearer. Se è scaduto o è stato revocato, utilizzare una credenziale autorizzata corrente; non incollarlo in chat. |
| 403 | Controllare identity.scopes per google_search e l'accesso per pronto. Richiedere il permesso mancante dal proprietario; cambiare la fonte nella richiesta non garantisce l'accesso. |
| 402 | Leggi di nuovo l'equilibrio e confrontalo con il prezzo attuale. Il proprietario può controllare Billing. Una prova esausta ha bisogno di accesso del proprietario attraverso la rivendicazione; la creazione di una prova sostitutivo non è il recupero. |
| 400 / 422 | Leggi il messaggio di errore restituito. Controllare l'host dati esatto, il metodo POST, i nomi dei campi Content-Type e JSON. Utilizzare le citazioni rette e una params.num numerico, quindi correggere la richiesta rifiutata. |
| 429 | Rispettare Retry-After se presente; altrimenti utilizzare un backoff limitato e ridurre la convalutazione. Non loop rapidamente, creare nuove chiavi o registrare un altro prova per bypassare il limite. |
| HTTP 200 con stato o errore guasti | Leggi l'errore nel corpo e conserva qualsiasi richiesta o lavoro ID. Non trattare un corpo di JSON parso come un compito di successo o resubmit automaticamente. |
| Risultati vuoti | Se lo stato è fatto, l'autenticazione ha funzionato. Mantenere il risultato vuoto o provare una domanda più ampia come una nuova richiesta a pagamento. |
| Timeout, perdita di connessione, 5xx o HTML invece di JSON | A POST può essere stato accettato anche se la sua risposta è stata persa. Controllare History per la query originale e conservare qualsiasi IDs restituito prima di decidere di rivendere. I controlli GET gratuiti possono essere riattivati. Confermare che URL utilizza data.flashdata.dev, non l'host del sito web, e non disabilitare la verifica TLS. |

- [Richiedi la cronologia](https://flashdata.dev/app/jobs)
- [Gestione delle chiavi](https://flashdata.dev/app/api-keys)
- [Download cURL](https://curl.se/download.html)
- [Installare PowerShell](https://learn.microsoft.com/powershell/scripting/install/installing-powershell)
- [Download Node.js](https://nodejs.org/en/download)
- [Download Python](https://www.python.org/downloads/)
