Google Search API in C# and .NET: Get Google Results with HttpClient
If your HttpClient gives up at 30 seconds, the search can still be counted and you get nothing back. Fetch Google results in C# with HttpClient and the JustSERP API: records, a 90 second timeout, retries and SemaphoreSlim concurrency.
Most .NET snippets that call a search API set HttpClient.Timeout to 30 seconds, and that is a small bug. A hard Google query can keep us working for over a minute, and if your client hangs up first, the call is still counted and the answer is lost. I'll show you how to fetch Google results in C# with the JustSERP API using HttpClient, records and SemaphoreSlim, with timeouts that hold up. It uses only the base class library, so there is no NuGet package to add.

What you need
- The .NET 6 SDK or newer. The examples use top-level statements, records and nullable reference types, which the default
dotnet new consoletemplate enables. - A JustSERP API key. Sign up, then copy the key from your dashboard.
Keep the key out of your source code and read it from an environment variable:
export JUSTSERP_API_KEY="your-key-here" # PowerShell: $env:JUSTSERP_API_KEY = "your-key-here"Call the API from your server, never from client-side code. A Blazor WebAssembly or MAUI app ships its code to the user, so the key would be exposed. Call JustSERP from an ASP.NET Core endpoint, a worker service or a console job and send your own front end the results.
How a request works
You send a keyword and any options as JSON to https://api.justserp.com/v1/search. We fetch the Google results page, parse it, and return clean JSON. One request returns one results page, typically in 2 to 4 seconds. When Google pushes back, we retry the fetch before giving up, which is why a hard query can run long and why the timeout in this guide is 90 seconds.
On every request we also ask Google for unfiltered, non-personalised results. You get the full list without the "similar results omitted" notice and without anyone's search history shaping it. We do not cache searches, so each call is a fresh fetch.

Your first request
Send the key in the X-API-Key header and the search in the JSON body. Only keyword is required. This is a complete Program.cs:
using System.Net.Http.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(90) };
http.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("JUSTSERP_API_KEY"));
using var response = await http.PostAsJsonAsync(
"https://api.justserp.com/v1/search",
new { keyword = "best coffee grinder" });
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"{(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
return;
}
var data = await response.Content.ReadFromJsonAsync<SerpResponse>();
foreach (var result in data?.OrganicResults ?? new List<Result>())
{
Console.WriteLine($"{result.Position}. {result.Title}");
Console.WriteLine($" {result.Link}");
}
public record Result(int Position, string Title, string Link);
public record SerpResponse(
[property: System.Text.Json.Serialization.JsonPropertyName("organic_results")] List<Result>? OrganicResults);
Always set a timeout, and make it 90 seconds. HttpClient already waits 100 seconds by default, so the point is to choose a value on purpose rather than copy 30 from a snippet. Also create one client and reuse it rather than creating one per request, so connections are pooled.
What comes back: records
The answer is a JSON object. A block only appears when Google showed it on that page, so make optional blocks nullable and fall back to an empty list. PostAsJsonAsync and ReadFromJsonAsync use camelCase and case-insensitive matching by default, so only the snake_case names need an attribute. Put the models in Models.cs:
using System.Text.Json.Serialization;
public record Result(int Position, string Title, string Link, string? Description);
public record Meta(int Status, string? Query, string? Device, string? GoogleUrl);
public record SerpResponse(
Meta Meta,
[property: JsonPropertyName("organic_results")] List<Result>? OrganicResults,
[property: JsonPropertyName("paid_ads")] List<Result>? PaidAds,
[property: JsonPropertyName("related_questions")] List<string>? RelatedQuestions,
[property: JsonPropertyName("related_search")] List<string>? RelatedSearch);
public record SearchRequest(
string Keyword,
string? Country = null,
string? Language = null,
string? Location = null,
int? Page = null,
string? Device = null,
string? Tbs = null,
string? Nfpr = null,
bool? Html = null);
Fields you do not declare, such as knowledge_graph or inline_videos, are ignored until you add them. A few quirks: paid_ads is one list in page order with no top or bottom flag, related_questions holds the question text only, and mobile answers have no inline_videos or totalResults.
A reusable client
This class holds one HttpClient, serializes a SearchRequest without its null options so the defaults apply, and throws a JustSerpException on failure. Put it in JustSerpClient.cs:
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
public sealed class JustSerpException : Exception
{
public int Status { get; }
public JustSerpException(string message, int status) : base(message) => Status = status;
}
public sealed class JustSerpClient : IDisposable
{
private const string Url = "https://api.justserp.com/v1/search";
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
private readonly HttpClient _http;
public JustSerpClient(string apiKey)
{
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(90) };
_http.DefaultRequestHeaders.Add("X-API-Key", apiKey);
}
public async Task<SerpResponse> SearchAsync(SearchRequest request, CancellationToken ct = default)
{
using var response = await _http.PostAsJsonAsync(Url, request, Json, ct);
if (!response.IsSuccessStatusCode)
{
var body = await response.Content.ReadAsStringAsync(ct);
throw new JustSerpException($"HTTP {(int)response.StatusCode}: {body}", (int)response.StatusCode);
}
return (await response.Content.ReadFromJsonAsync<SerpResponse>(Json, ct))!;
}
public void Dispose() => _http.Dispose();
}
Advanced parameters
Every option is a property on SearchRequest, and any you leave out is not sent.

Country, language and location
country (default "United States") and language (default "English") take full English names such as "United Kingdom" or "Germany", not codes like "UK" or "de". A name we don't recognise is not an error. It falls back to United States and English, and the call is still used. When results look wrong, check Meta.GoogleUrl to see which Google domain was really used.
For "near me" searches use location, a city in Google's canonical City,Region,Country form. We turn it into Google's uule parameter as-is and do not validate it. A misspelled location is not rejected: Google ignores it, you get non-local results and the call is used. location does not change the Google domain or language either, so send a matching country as well. You can also send a ready-made uule string, and location wins when both are present.
using var client = new JustSerpClient(Environment.GetEnvironmentVariable("JUSTSERP_API_KEY")!);
var french = await client.SearchAsync(new SearchRequest("assurance auto", Country: "France", Language: "French"));
var local = await client.SearchAsync(new SearchRequest("plumber near me", Country: "United States", Location: "Austin,Texas,United States"));
Pagination, devices, time filters and exact queries
Page: 2 returns the second page. It overrides start: page N becomes start=(N-1)*10. Each page uses one API call. Position restarts at 1 on every page, so the absolute rank is (page - 1) * 10 + position, provided Google returned ten organic results on that page. Device is "desktop" or "mobile". Tbs is passed straight to Google, so qdr:d is the past day and qdr:w the past week. Nfpr set to "1" turns off Google's auto-correction. Both must be strings, which is why the properties are string?.
var ranks = new Dictionary<string, int>();
foreach (var page in new[] { 1, 2, 3 })
{
var data = await client.SearchAsync(new SearchRequest("project management software", Page: page, Device: "mobile"));
foreach (var item in data.OrganicResults ?? new List<Result>())
ranks.TryAdd(item.Link, (page - 1) * 10 + item.Position);
}
foreach (var (link, rank) in ranks.OrderBy(kv => kv.Value).Take(5).Select(kv => (kv.Key, kv.Value)))
Console.WriteLine($"{rank} {link}");
var news = await client.SearchAsync(new SearchRequest("openai announcement", Tbs: "qdr:d"));
var exact = await client.SearchAsync(new SearchRequest("justserp", Nfpr: "1"));
Set Html: true if you also want the raw Google page. Add a string? Html property to SerpResponse to read it. Responses get much larger, so only use it when you need it. The q alias also works in place of keyword, and unknown fields are ignored without a warning.
Handling errors, and what is billed
Check the HTTP status before you read the body:
| Status | Meaning | What to do |
|---|---|---|
200 | Success. One API call is used. | Read the results. |
400 | Invalid parameters. No call is used. | Fix the request. Do not retry it unchanged. |
401 | The API key is missing or invalid. | Check the X-API-Key header. |
429 | You have no API calls left. | Top up or upgrade your plan. |
500 | The page could not be fetched. No call is used. | Retry after a short pause. |
A 200 uses a call. A 400, a 500 or another server error does not, and a 401 or 429 never counts. Retrying a failure costs nothing, with one catch: a request your own client abandons is still counted, so a timeout retry can cost a call. A 500 reaches you only after we have retried on our side. Add this method to JustSerpClient. It retries a 500, network errors and timeouts with a growing delay, and lets 400, 401 and 429 fail at once:
public async Task<SerpResponse> SearchWithRetryAsync(
SearchRequest request, int retries = 3, CancellationToken ct = default)
{
for (var attempt = 0; ; attempt++)
{
try
{
return await SearchAsync(request, ct);
}
catch (Exception ex) when (IsRetryable(ex) && attempt < retries)
{
await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)), ct); // 1s, 2s, 4s...
}
}
}
private static bool IsRetryable(Exception ex) =>
ex is JustSerpException { Status: 500 }
or HttpRequestException
or TaskCanceledException { InnerException: TimeoutException };
Running many searches with SemaphoreSlim
Each search takes a few seconds, so running them concurrently multiplies your throughput. Your plan sets how many requests may be in flight together: 10 on Free and Personal, 25 on Business, 50 on Enterprise. That counts requests in progress, not requests per second. A SemaphoreSlim keeps you within that limit while every keyword runs as its own task. Add this to JustSerpClient too:
public record Outcome(string Keyword, int Count, string? Error);
public async Task<IReadOnlyList<Outcome>> SearchManyAsync(
IEnumerable<string> keywords, int maxConcurrency, CancellationToken ct = default)
{
using var gate = new SemaphoreSlim(maxConcurrency);
var tasks = keywords.Select(async keyword =>
{
await gate.WaitAsync(ct);
try
{
var data = await SearchWithRetryAsync(new SearchRequest(keyword), ct: ct);
return new Outcome(keyword, data.OrganicResults?.Count ?? 0, null);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return new Outcome(keyword, 0, ex.Message);
}
finally
{
gate.Release();
}
}).ToList();
return await Task.WhenAll(tasks);
}
Only maxConcurrency requests run at once, however long the list is, and Task.WhenAll returns the results in the order of the input. Use it from Program.cs. The overall deadline is generous on purpose, because one request may use up to 90 seconds:
using var client = new JustSerpClient(Environment.GetEnvironmentVariable("JUSTSERP_API_KEY")!);
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
var keywords = new[] { "crm software", "email marketing tool", "invoice app", "seo checker" };
foreach (var o in await client.SearchManyAsync(keywords, maxConcurrency: 5, cts.Token))
{
Console.WriteLine(o.Error is null ? $"{o.Keyword}: {o.Count} results" : $"{o.Keyword}: {o.Error}");
}
Habits that save calls and headaches
- Call the API from the server and keep the key in an environment variable, user secrets or a key vault, never in source control.
- Reuse one client (or inject
IHttpClientFactoryin ASP.NET Core) and set the timeout to 90 seconds. - Pass a
CancellationTokenso requests stop when a caller gives up or your service shuts down. Remember that an abandoned request can still be counted. - Cache results you will reuse, with
IMemoryCacheor Redis. We do not cache searches, so a repeated search is a repeated call. - Keep
maxConcurrencywithin your plan's limit, so requests are never rejected for sending too many at once.
Next steps
That covers what you need to put Google data into your .NET services. Create a free account for 2,000 free requests, no credit card needed, and try the examples above, or see the pricing when you are ready to scale. Prefer another language? Read the Python version of this guide or the JavaScript version.