Code, examples and project builder
Everything to get started with the Polias Search API: example projects
that run as soon as you add your key, a builder that puts together the project you need, and snippets in
many languages. Free to use, modify and share, also commercially, no attribution required (MIT-0 license).
Provided without warranty: you are responsible for using it.
Get a key with 1,000 free searches a month at /schnittstelle.
In the snippets, replace pol_YOUR_API_KEY with your key; the projects read it from the file .env.
Important: keep the key on your server, never in code that runs in your visitors' browser, where anyone could read it and search at your expense. Beyond the 1,000 free searches a month, every search costs one search from your credit.
Code, Beispiele und Baukasten
Alles für den Einstieg in die Polias Such-Schnittstelle: Beispiel-Projekte,
die laufen, sobald Ihr Schlüssel drin ist, ein Baukasten, der Ihnen das passende Projekt zusammenstellt, und
Bausteine in vielen Sprachen. Sie dürfen alles frei verwenden, ändern und weitergeben, auch kommerziell, ohne
Namensnennung (Lizenz MIT-0). Ohne Gewähr: Für den Einsatz sind Sie selbst verantwortlich.
Einen Schlüssel mit 1.000 kostenlosen Suchen im Monat bekommen Sie unter /schnittstelle.
In den Bausteinen kommt Ihr Schlüssel überall dort hinein, wo pol_YOUR_API_KEY steht; die Projekte lesen ihn aus der Datei .env.
Wichtig: Der Schlüssel gehört auf Ihren Server, nie in Code, der im Browser der Besucher läuft. Sonst kann ihn jeder auslesen und auf Ihre Kosten suchen. Jede Suche über die 1.000 kostenlosen im Monat hinaus zieht eine Suche vom Guthaben.
Ready package, no codingFertig-Paket, ohne Programmieren
Click together what you need, enter your key once, download. Double-click to start, it runs.
Zusammenklicken, was Sie brauchen, Schlüssel einmal eingeben, herunterladen. Doppelklick, läuft.
I write codeIch programmiere
Example projects, a project builder and snippets in Python, JavaScript, PHP, Go, Java, C#, Ruby and more.
Beispiel-Projekte, Baukasten und Bausteine in Python, JavaScript, PHP, Go, Java, C#, Ruby und mehr.
Ready package: three steps, then it runsFertig-Paket: drei Schritte, dann läuft es
- Ready packageFertig-Paket
- Example projectsBeispiel-Projekte
- Project builderBaukasten
- Web, news, legal, officialWeb, News, Recht, amtlich
- SnippetsBausteine
- AI agents and toolsKI-Agenten und Werkzeuge
- Search page (PHP)Suchseite (PHP)
Example projects: unpack, add key, runBeispiel-Projekte: auspacken, Schlüssel rein, läuft
Each ZIP is a small, complete project without extra packages (Python 3.8+ or Node.js 18+). Open the file
.env, paste your key, start it. The README inside explains every step. Want something different?
Open the example in the builder and change what you need.
Jedes ZIP ist ein kleines, fertiges Projekt ohne weitere Pakete (Python 3.8+ oder Node.js 18+). Datei
.env öffnen, Schlüssel einfügen, starten. Die README darin erklärt jeden Schritt. Sie brauchen
etwas anderes? Öffnen Sie das Beispiel im Baukasten und ändern Sie, was Sie brauchen.
Legal research assistantRechts-Assistent
Chatbot in the browser: finds court decisions and web pages for a legal question and answers with numbered sources, using a language model of your choice.
Chatbot im Browser: sucht Gerichtsentscheidungen und Webseiten zu einer Rechtsfrage und antwortet mit nummerierten Quellen, über ein Sprachmodell Ihrer Wahl.
ZIPDocs search for coding agentsDoku-Suche für Coding-Agents
A local MCP server: Claude, Cursor or VS Code search developer documentation, programming and IT pages in English.
Ein lokaler MCP-Server: Claude, Cursor oder VS Code durchsuchen Entwickler-Dokumentation, Programmier- und IT-Seiten auf Englisch.
ZIPNews feed (RSS)Nachrichten-Feed (RSS)
News of the last 30 days on your topic as a list, as JSON or as an RSS feed for any feed reader, e.g. every morning.
Nachrichten der letzten 30 Tage zu Ihrem Thema als Liste, als JSON oder als RSS-Feed für jeden Feedreader, z. B. jeden Morgen.
ZIPCitizen service chatbotBürger-Chatbot
Answers questions about local services only from official websites, the local authority first (example: Köln).
Beantwortet Fragen zu Ämtern und Diensten nur aus amtlichen Websites, die Behörde vor Ort zuerst (Beispiel: Köln).
ZIPMeta searchMetasuche
Polias as an additional source next to your others: asks all at once, merges the results and removes duplicates. Web page and JSON.
Polias als zusätzliche Quelle neben Ihren anderen: fragt alle zugleich, mischt die Treffer und entfernt doppelte. Webseite und JSON.
ZIPAI search with licencesKI-Suche mit Lizenzen
The AI search: results with licence details and, where the licence allows it, a longer extract with attribution.
Die KI-Suche: Treffer mit Lizenzangaben und, wo die Lizenz es erlaubt, einem längeren Auszug mit Namensnennung.
ZIPProject builder: tick, download, runBaukasten: anklicken, herunterladen, starten
Choose what you want to search and what you want to build. The page puts the project together from tested templates, right here in your browser: nothing is sent, and your key is not needed until you run it.
Wählen Sie, was gesucht werden soll und was Sie bauen wollen. Die Seite setzt das Projekt aus getesteten Vorlagen zusammen, direkt in Ihrem Browser: Es wird nichts gesendet, und Ihren Schlüssel brauchen Sie erst beim Starten.
Try it in one minuteIn einer Minute ausprobieren
In a terminal (Windows: PowerShell with curl.exe, Mac and Linux: curl):
Im Terminal (Windows: PowerShell mit curl.exe, Mac und Linux: curl):
curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/search?q=python+asyncio&lang=en&count=3"
Web, news, legal, official: result_filterWeb, Nachrichten, Recht, amtlich: result_filter
With result_filter you choose what a search returns, several areas separated by commas
(German alias: bereich). Each area comes as its own block in the answer. At most 10 results per
request, however many areas you tick, and every request counts as one search.
web: web searchnews: news articles of the last 30 days (lang=deoren). For press articles we show title, link and the publisher's short teaser (max. 160 characters), some publishers title and link only.recht: Polias Recht, court decisions and EU law from Germany, Austria, Switzerland and the EU, also Spain and the Netherlands (land=de,at,ch,eu,es,nl,art=e.g.entscheid). Every result carrieshinweis(source and licence): please show it with the result.amtlich: only official websites in Germany, Austria, Switzerland and the EU (authorities, municipalities, districts, ministries, courts, chambers), currentlylang=deonly. Addort=to prefer the local authority. Not together withweb, becauseamtlichalready is the web search restricted to official sources; withnewsandrechtit works.
Without result_filter nothing changes: web search as one list results, with matching
legal results mixed in for case numbers and citations. With web and no share given, news and
legal results only come when they fit the query; news_count and recht_count fix
a share, and the web search fills the rest. Without web the chosen areas share the places.
If one area is briefly unavailable, the others still come and its block carries "error".
Mit result_filter wählen Sie, was eine Suche liefert, mehrere Bereiche mit Komma getrennt
(deutscher Name gleichwertig: bereich). Jeder Bereich kommt als eigener Block in der Antwort.
Höchstens 10 Treffer je Anfrage, egal wie viele Bereiche Sie wählen, und jede Anfrage zählt als eine Suche.
web: Websuchenews: Nachrichtenartikel der letzten 30 Tage (lang=deoderen). Bei Presseartikeln zeigen wir Titel, Link und den kurzen Anreißer des Verlags (höchstens 160 Zeichen), bei manchen Verlagen nur Titel und Link.recht: Polias Recht, Gerichtsentscheidungen und EU-Recht aus Deutschland, Österreich, der Schweiz und der EU, dazu Spanien und die Niederlande (land=de,at,ch,eu,es,nl,art=z. B.entscheid). Jeder Treffer hat das Feldhinweis(Quelle und Lizenz): bitte mit anzeigen.amtlich: nur Treffer von amtlichen Websites in Deutschland, Österreich, der Schweiz und der EU (Behörden, Gemeinden, Landkreise, Ministerien, Gerichte, Kammern), derzeit nur mitlang=de. Mitort=bevorzugen Sie die Behörde vor Ort. Nicht zusammen mitweb, weilamtlichschon die Websuche auf amtlichen Quellen ist; mitnewsundrechtgeht es.
Ohne result_filter bleibt alles wie bisher: Websuche als eine Liste results, bei
Aktenzeichen und Normzitaten mit passenden Rechtstreffern darin. Ist web dabei und Sie geben
keinen Anteil an, kommen Nachrichten und Rechtstreffer nur, wenn sie zur Suche passen; mit
news_count und recht_count legen Sie den Anteil fest, die Websuche füllt auf. Ohne
web teilen sich die gewählten Bereiche die Plätze. Ist ein Bereich kurz nicht erreichbar, kommen
die anderen trotzdem, und sein Block trägt "error".
# Only news of the last 30 days (lang=de or en): block "news", every article with page_age curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/search?q=bundestag&result_filter=news&count=5" # Only legal (Polias Recht): block "recht" with gericht, aktenzeichen, datum, leitsatz and hinweis (source, licence) curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/search?q=eigenbedarf+kuendigung&result_filter=recht&land=de" # Only official websites in DE, AT, CH and the EU, the local authority first (lang=de) curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/search?q=hundesteuer&ort=Graz&result_filter=amtlich" # Web results plus exactly 3 legal results curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/search?q=mietminderung+heizung&result_filter=web,recht&recht_count=3" # Web, news and legal in one request: at most 10 results in total, one request = one search curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/search?q=energiewende&result_filter=web,news,recht"
Answer with blocks (shortened):Antwort mit Blöcken (gekürzt):
{
"query": "kündigung eigenbedarf",
"lang": "de",
"result_filter": ["web", "recht"],
"web": {
"results": [
{ "position": 1, "title": "…", "url": "https://…", "snippet": "… (max. 160 characters)", "hostname": "www.…" }
],
"total": 1234
},
"recht": {
"results": [
{ "position": 1, "title": "BGH, Urteil vom 20. März 2013 - VIII ZR 233/12", "url": "https://…",
"snippet": "…", "hostname": "…", "land": "de", "art": "entscheid", "gericht": "BGH",
"aktenzeichen": "VIII ZR 233/12", "datum": "2013-03-20", "entscheidungsart": "Urteil",
"leitsatz": "Eine Kündigung von Wohnraum wegen Eigenbedarfs …", "normen": ["§ 573 Abs 2 Nr 2 BGB"],
"lizenz": "…", "hinweis": "Quelle: Rechtsinformationsportal des Bundes, rechtsinformationen.bund.de" }
]
},
"corrected": "", "suggestion": "", "took_ms": 140,
"usage": { "today": 12, "month": 340 }
}
AI search: /v1/kiKI-Suche: /v1/ki
Same key, same credit. Each result additionally has lizenz and ki_training and, where
the licence allows it, a longer extract auszug with attribution namensnennung.
Parameters as above: q, lang, count, ort and result_filter
with web, news, recht, amtlich; the news block is called nachrichten here.
Gleicher Schlüssel, gleiches Guthaben. Jeder Treffer hat zusätzlich lizenz und
ki_training und, wo die Lizenz es erlaubt, einen längeren Auszug auszug mit
Namensnennung namensnennung. Angaben wie oben: q, lang, count, ort und result_filter
mit web, news, recht, amtlich; der Nachrichten-Block heißt hier nachrichten.
# AI search: like the web search, plus licence details per result and, where the licence allows it,
# a longer extract ("auszug") with attribution ("namensnennung")
curl -H "Authorization: Bearer pol_YOUR_API_KEY" "https://api.polias.eu/v1/ki?q=photosynthese&count=5"
SnippetsBausteine
One function each that searches and returns the results, with an example call, only with what the language
brings along. The key is read from the environment variable POLIAS_API_KEY.
Je eine Funktion, die sucht und die Treffer zurückgibt, mit einem Beispielaufruf, nur mit dem, was die Sprache
mitbringt. Der Schlüssel kommt aus der Umgebungsvariable POLIAS_API_KEY.
Python
import json
import os
import urllib.parse
import urllib.request
API_KEY = os.environ.get("POLIAS_API_KEY", "pol_YOUR_API_KEY")
def polias_search(query, count=10, **params):
"""Search with Polias. params e.g. lang="en", land="at", ort="Graz", quelle="amtlich"."""
url = "https://api.polias.eu/v1/search?" + urllib.parse.urlencode({"q": query, "count": count, **params})
request = urllib.request.Request(url, headers={"Authorization": "Bearer " + API_KEY})
with urllib.request.urlopen(request, timeout=15) as response:
return json.load(response)["results"]
for result in polias_search("python list comprehension", count=3, lang="en"):
print(result["title"], "-", result["url"])
JavaScript (Node.js, server-sideauf dem Server)
// Node.js 18 or newer, on your server (never in the browser, where anyone could read the key).
const API_KEY = process.env.POLIAS_API_KEY || 'pol_YOUR_API_KEY';
async function poliasSearch(query, params = {}) {
const url = new URL('https://api.polias.eu/v1/search');
url.searchParams.set('q', query);
for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
const response = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } });
if (!response.ok) throw new Error(`Polias responded with ${response.status}`);
return (await response.json()).results;
}
for (const result of await poliasSearch('kubernetes pod lifecycle', { lang: 'en', count: 3 })) {
console.log(result.title, '-', result.url);
}
PHP
<?php
// PHP 7.4 or newer. Best keep the key in the environment variable POLIAS_API_KEY.
function polias_search(string $query, array $params = []): array
{
$apiKey = getenv('POLIAS_API_KEY') ?: 'pol_YOUR_API_KEY';
$url = 'https://api.polias.eu/v1/search?' . http_build_query(['q' => $query] + $params);
$context = stream_context_create(['http' => [
'header' => "Authorization: Bearer $apiKey\r\n",
'timeout' => 15,
'ignore_errors' => true,
]]);
$response = json_decode((string) @file_get_contents($url, false, $context), true);
return $response['results'] ?? [];
}
foreach (polias_search('Sperrmüll anmelden', ['ort' => 'Freiburg im Breisgau', 'count' => 3]) as $result) {
echo $result['title'], ' - ', $result['url'], "\n";
}
Go
// Go 1.18 or newer, standard library only: go run search.go
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
)
type Result struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
PageAge string `json:"page_age"`
}
func poliasSearch(query string, params url.Values) ([]Result, error) {
key := os.Getenv("POLIAS_API_KEY")
if key == "" {
key = "pol_YOUR_API_KEY"
}
params.Set("q", query)
req, _ := http.NewRequest("GET", "https://api.polias.eu/v1/search?"+params.Encode(), nil)
req.Header.Set("Authorization", "Bearer "+key)
resp, err := (&http.Client{Timeout: 15 * time.Second}).Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Polias responded with %d", resp.StatusCode)
}
var answer struct {
Results []Result `json:"results"`
}
err = json.NewDecoder(resp.Body).Decode(&answer)
return answer.Results, err
}
func main() {
results, err := poliasSearch("golang context cancellation", url.Values{"lang": {"en"}, "count": {"3"}})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, r := range results {
fmt.Println(r.Title, "-", r.URL)
}
}
Java
// Java 11 or newer, no libraries: java Search.java
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;
public class Search {
static final String API_KEY = Objects.requireNonNullElse(System.getenv("POLIAS_API_KEY"), "pol_YOUR_API_KEY");
// Returns the JSON answer as text; read it with the JSON library you already use (Jackson, Gson ...).
static String poliasSearch(String query, String params) throws Exception {
String url = "https://api.polias.eu/v1/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + params;
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.header("Authorization", "Bearer " + API_KEY)
.timeout(Duration.ofSeconds(15))
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) throw new RuntimeException("Polias responded with " + response.statusCode());
return response.body();
}
public static void main(String[] args) throws Exception {
System.out.println(poliasSearch("spring boot virtual threads", "&lang=en&count=3"));
}
}
C# / .NET
// C# / .NET 6 or newer: dotnet new console, replace Program.cs with this file, dotnet run
using System.Net.Http.Headers;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("POLIAS_API_KEY") ?? "pol_YOUR_API_KEY";
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
async Task<JsonElement> PoliasSearch(string query, string parameters = "")
{
var response = await http.GetAsync($"https://api.polias.eu/v1/search?q={Uri.EscapeDataString(query)}{parameters}");
if (!response.IsSuccessStatusCode) throw new Exception($"Polias responded with {(int)response.StatusCode}");
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.GetProperty("results");
}
foreach (var result in (await PoliasSearch("dotnet dependency injection", "&lang=en&count=3")).EnumerateArray())
Console.WriteLine($"{result.GetProperty("title")} - {result.GetProperty("url")}");
Ruby
# Ruby 2.7 or newer, standard library only: ruby search.rb
require "json"
require "net/http"
require "uri"
API_KEY = ENV.fetch("POLIAS_API_KEY", "pol_YOUR_API_KEY")
def polias_search(query, **params)
uri = URI("https://api.polias.eu/v1/search")
uri.query = URI.encode_www_form(q: query, **params)
request = Net::HTTP::Get.new(uri, "Authorization" => "Bearer #{API_KEY}")
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 15) { |http| http.request(request) }
raise "Polias responded with #{response.code}" unless response.code == "200"
JSON.parse(response.body)["results"]
end
polias_search("rails active record callbacks", lang: "en", count: 3).each do |result|
puts "#{result["title"]} - #{result["url"]}"
end
PowerShell
# PowerShell 5.1 or 7 (Windows, Mac, Linux). Key from the environment: $env:POLIAS_API_KEY = "pol_..."
$key = if ($env:POLIAS_API_KEY) { $env:POLIAS_API_KEY } else { "pol_YOUR_API_KEY" }
$query = [uri]::EscapeDataString("hundesteuer")
$answer = Invoke-RestMethod -Uri "https://api.polias.eu/v1/search?q=$query&ort=Graz&result_filter=amtlich&count=3" `
-Headers @{ Authorization = "Bearer $key" }
$answer.amtlich.results | ForEach-Object { "$($_.title) - $($_.url)" }
Use casesAnwendungsfälle
Several areas at once: news and web (Python)Mehrere Bereiche auf einmal: Nachrichten und Web (Python)
import json
import os
import urllib.parse
import urllib.request
API_KEY = os.environ.get("POLIAS_API_KEY", "pol_YOUR_API_KEY")
def polias_blocks(query, result_filter="web,news,recht", **params):
"""Returns {"web": [...], "news": [...], "recht": [...]} with the blocks you ticked."""
url = "https://api.polias.eu/v1/search?" + urllib.parse.urlencode({"q": query, "result_filter": result_filter, **params})
request = urllib.request.Request(url, headers={"Authorization": "Bearer " + API_KEY})
with urllib.request.urlopen(request, timeout=15) as response:
answer = json.load(response)
return {block: answer.get(block, {}).get("results", []) for block in result_filter.split(",")}
blocks = polias_blocks("energiewende", "web,news", news_count=3)
for article in blocks["news"]:
print(article["page_age"][:10], article["title"], article["url"])
for page in blocks["web"]:
print(page["title"], page["url"])
Legal search with court, case number and notice (JavaScript)Rechtssuche mit Gericht, Aktenzeichen und Hinweis (JavaScript)
// Legal search (Polias Recht): court decisions and EU law from DE, AT, CH and the EU (also ES, NL). Node.js 18+.
const API_KEY = process.env.POLIAS_API_KEY || 'pol_YOUR_API_KEY';
async function legalSearch(query, land = 'de') {
const url = new URL('https://api.polias.eu/v1/search');
url.search = new URLSearchParams({ q: query, result_filter: 'recht', land, count: 5 });
const response = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } });
if (!response.ok) throw new Error(`Polias responded with ${response.status}`);
return (await response.json()).recht.results;
}
for (const hit of await legalSearch('Kündigung wegen Eigenbedarf')) {
console.log(`${hit.gericht ?? ''} ${hit.aktenzeichen ?? ''} (${hit.datum ?? ''}): ${hit.title}`);
console.log(` ${hit.leitsatz || hit.snippet}`);
console.log(` ${hit.url}\n ${hit.hinweis}`); // please show the notice (source and licence) with the result
}
More pages and clean error handling (Python)Mehrere Seiten und saubere Fehlerbehandlung (Python)
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
API_KEY = os.environ.get("POLIAS_API_KEY", "pol_YOUR_API_KEY")
def polias_get(params, tries=3):
"""One request with clear errors; waits and tries again on 429 (Retry-After)."""
url = "https://api.polias.eu/v1/search?" + urllib.parse.urlencode(params)
request = urllib.request.Request(url, headers={"Authorization": "Bearer " + API_KEY})
try:
with urllib.request.urlopen(request, timeout=15) as response:
return json.load(response)
except urllib.error.HTTPError as error:
if error.code == 429 and tries > 1:
time.sleep(int(error.headers.get("Retry-After") or 2))
return polias_get(params, tries - 1)
message = {401: "wrong key", 402: "free searches and credit used up", 403: "key bound to other IP addresses"}
raise RuntimeError(f"Polias {error.code}: {message.get(error.code, error.read().decode()[:200])}") from None
def polias_pages(query, pages=3, **params):
"""Up to 100 results: 10 per page, offset 0, 10, 20 ... (each page is one search)."""
for page in range(pages):
results = polias_get({"q": query, "count": 10, "offset": page * 10, **params})["results"]
yield from results
if len(results) < 10:
break
for number, result in enumerate(polias_pages("rust ownership", pages=2, lang="en"), 1):
print(number, result["title"], result["url"])
AI agents and toolsKI-Agenten und Werkzeuge
No coding: a brief for your AIOhne Programmieren: Auftrag für Ihre KI
Working with an AI assistant that can write code? Paste this text and describe what you need in the last line. It contains everything the AI needs to know about our API.
Sie arbeiten mit einem KI-Assistenten, der Code schreiben kann? Kopieren Sie diesen Text hinein und beschreiben Sie in der letzten Zeile, was Sie brauchen. Darin steht alles, was die KI über unsere Schnittstelle wissen muss.
Please add search to my project using the Polias Search API. This is how it works:
- Endpoint: GET https://api.polias.eu/v1/search
- Header: Authorization: Bearer pol_YOUR_API_KEY
The key must stay on the server (environment variable POLIAS_API_KEY), never in browser code.
- Query parameters:
q (search term, required, max. 200 characters), count (1 to 10), offset (0 to 90, 10 = page 2),
lang (de or en; en focuses on technical topics), land (prefer de, at or ch),
ort (a municipality in DE, AT or CH, only with lang=de),
result_filter (what to search, comma-separated: web, news = news of the last 30 days, recht = court decisions
and EU law, amtlich = official websites only, lang=de only, not together with web; at most 10 results in total,
news_count/recht_count fix a share)
- Response (JSON) without result_filter: {"results": [{"position", "title", "url", "snippet", "hostname", "page_age"}]}
With result_filter one block per area: {"web": {"results": [...]}, "news": {"results": [...]}, ...}
page_age (publication time) is only present for news. Legal results also have gericht, aktenzeichen, datum,
leitsatz and hinweis (source and licence, show it with the result).
- AI search: GET https://api.polias.eu/v1/ki?q=...&lang=de|en&count=... (same key) returns {"web": [{"titel", "url",
"website", "ausschnitt", "lizenz", "auszug", "namensnennung"}]}: licence details and, where the licence allows it,
a longer extract with attribution.
- Errors: 400 invalid request, 401 wrong key, 403 key bound to fixed IP addresses, 402 free allowance and credit used up, 429 too many searches per minute or daily limit reached
(wait briefly), 503 temporarily unavailable.
- Beyond the 1,000 free searches a month, every search costs one search from the credit. Escape titles and snippets before showing them as HTML.
What I want: [describe it here, e.g. "a search box on our website that shows only official results for our
town" or "a script that searches for new articles on a topic every morning"].Bitte baue mir eine Suche mit der Polias-Such-Schnittstelle ein. So funktioniert sie:
- Adresse: GET https://api.polias.eu/v1/search
- Schlüssel im Kopf: Authorization: Bearer pol_YOUR_API_KEY
Der Schlüssel darf nur auf dem Server stehen (Umgebungsvariable POLIAS_API_KEY), nie im Browser-Code.
- Angaben in der Adresse:
q (Suchbegriff, Pflicht, höchstens 200 Zeichen), count (1 bis 10), offset (0 bis 90, 10 = Seite 2),
lang (de oder en; en hat den Schwerpunkt Technik), land (de, at oder ch bevorzugen),
ort (eine Gemeinde in DE, AT oder CH, nur bei lang=de),
result_filter (was gesucht wird, mit Komma: web, news = Nachrichten der letzten 30 Tage, recht = Gerichts-
entscheidungen und EU-Recht, amtlich = nur amtliche Websites, nur bei lang=de, nicht zusammen mit web; zusammen
höchstens 10 Treffer, news_count/recht_count legen einen festen Anteil fest)
- Antwort (JSON) ohne result_filter: {"results": [{"position", "title", "url", "snippet", "hostname", "page_age"}]}
Mit result_filter je Bereich ein Block: {"web": {"results": [...]}, "news": {"results": [...]}, ...}
page_age (Erscheinungszeit) gibt es nur bei Nachrichten. Rechtstreffer haben zusätzlich gericht, aktenzeichen,
datum, leitsatz und hinweis (Quelle und Lizenz, bitte mit anzeigen).
- KI-Suche: GET https://api.polias.eu/v1/ki?q=...&lang=de|en&count=... (gleicher Schlüssel) liefert {"web": [{"titel",
"url", "website", "ausschnitt", "lizenz", "auszug", "namensnennung"}]}: Lizenzangaben und, wo die Lizenz es erlaubt,
einen längeren Auszug mit Namensnennung.
- Fehler: 400 Anfrage ungültig, 401 Schlüssel falsch, 403 Schlüssel an feste IP-Adressen gebunden, 402 kostenloses Kontingent und Guthaben leer, 429 zu viele Suchen je Minute oder Tageslimit erreicht
(kurz warten), 503 vorübergehend nicht verfügbar.
- Jede Suche über die 1.000 kostenlosen im Monat hinaus zieht eine Suche vom Guthaben. Titel und Ausschnitte bitte beim Anzeigen HTML-sicher machen.
Was ich will: [hier beschreiben, z. B. „ein Suchfeld auf unserer Website, das nur amtliche Treffer für unsere
Gemeinde zeigt“ oder „ein Skript, das jeden Morgen nach neuen Meldungen zu einem Thema sucht“].Connect AI assistants (MCP)KI-Assistenten anbinden (MCP)
Our hosted MCP server, nothing to install: your AI assistant searches Polias itself (web search, also
quelle=amtlich). For news and legal results take the local MCP server from the
builder. More programs (Open WebUI, LibreChat, n8n …) in the
developer guide.
Unser MCP-Server, ohne Installation: Ihr KI-Assistent sucht selbst bei Polias (Websuche, auch
quelle=amtlich). Für Nachrichten und Recht nehmen Sie den lokalen MCP-Server aus dem
Baukasten. Weitere Programme (Open WebUI, LibreChat, n8n …) in der
Anleitung.
Claude Code
claude mcp add --transport http polias https://api.polias.eu/mcp --header "Authorization: Bearer pol_YOUR_API_KEY"
Cursor (.cursor/mcp.json)
{
"mcpServers": {
"polias": {
"url": "https://api.polias.eu/mcp",
"headers": { "Authorization": "Bearer pol_YOUR_API_KEY" }
}
}
}
Visual Studio Code (.vscode/mcp.json)
{
"servers": {
"polias": {
"type": "http",
"url": "https://api.polias.eu/mcp",
"headers": { "Authorization": "Bearer pol_YOUR_API_KEY" }
}
}
}
As a tool in your own agent (function calling)Als Werkzeug im eigenen Agenten (Function Calling)
The tool definition in the common JSON format (OpenAI, Mistral and compatible APIs; for other providers take
parameters as the input schema), and the code that runs the tool call.
Die Werkzeug-Beschreibung im üblichen JSON-Format (OpenAI, Mistral und kompatible Schnittstellen; bei anderen
Anbietern parameters als Eingabe-Schema nehmen), dazu der Code, der den Werkzeug-Aufruf ausführt.
{
"type": "function",
"function": {
"name": "polias_search",
"description": "Search the web with Polias, a European search engine with its own index. Returns title, link and a short snippet per result. Use result_filter to get only news, legal results (court decisions, EU law) or official websites.",
"parameters": {
"type": "object",
"properties": {
"q": { "type": "string", "description": "Search query, a few keywords, max. 200 characters" },
"result_filter": { "type": "string", "description": "Comma-separated: web, news, recht (legal), amtlich (official websites, German only). amtlich cannot be combined with web." },
"lang": { "type": "string", "enum": ["de", "en"], "description": "de (default) or en (English, technical topics)" },
"count": { "type": "integer", "minimum": 1, "maximum": 10 }
},
"required": ["q"]
}
}
}
# Your agent calls the tool (definition above), your code runs the search and gives the result back.
import json
import os
import urllib.parse
import urllib.request
API_KEY = os.environ.get("POLIAS_API_KEY", "pol_YOUR_API_KEY")
def polias_search(q, result_filter="web", lang="de", count=5):
"""Runs a polias_search tool call and returns short text for the language model."""
params = {"q": q, "result_filter": result_filter, "lang": lang, "count": count}
url = "https://api.polias.eu/v1/search?" + urllib.parse.urlencode(params)
request = urllib.request.Request(url, headers={"Authorization": "Bearer " + API_KEY})
with urllib.request.urlopen(request, timeout=15) as response:
answer = json.load(response)
lines = []
for block in result_filter.split(","):
for hit in answer.get(block, {}).get("results", []):
lines.append(f"[{block}] {hit['title']}\n{hit['url']}\n{hit.get('leitsatz') or hit['snippet']}\n{hit.get('hinweis', '')}".strip())
return "\n\n".join(lines) or "No results."
# Example: the model asked for {"q": "...", "result_filter": "news"}
arguments = json.loads('{"q": "ki verordnung", "result_filter": "news", "count": 3}')
print(polias_search(**arguments))
LangChain / LangGraph
# pip install langchain-core (works with any LangChain agent or LangGraph)
import json
import os
import urllib.parse
import urllib.request
from langchain_core.tools import tool
API_KEY = os.environ.get("POLIAS_API_KEY", "pol_YOUR_API_KEY")
@tool
def polias_search(query: str, result_filter: str = "web", lang: str = "de") -> str:
"""Search Polias, a European search engine. result_filter: web, news, recht (legal) or amtlich (official
websites, German only), comma-separated. lang: de or en (English, technical topics)."""
url = "https://api.polias.eu/v1/search?" + urllib.parse.urlencode({"q": query, "result_filter": result_filter, "lang": lang, "count": 5})
request = urllib.request.Request(url, headers={"Authorization": "Bearer " + API_KEY})
with urllib.request.urlopen(request, timeout=15) as response:
answer = json.load(response)
hits = [hit for block in result_filter.split(",") for hit in answer.get(block, {}).get("results", [])]
return "\n\n".join(f"{hit['title']}\n{hit['url']}\n{hit['snippet']}" for hit in hits) or "No results."
print(polias_search.invoke({"query": "fastapi dependency injection", "lang": "en"}))
Ready-made search page for your websiteFertige Suchseite für Ihre Website
A single PHP file with search box, result list and “More results”, no dependencies. Made for municipalities,
associations or companies that want to offer search on their website. Save it e.g. as search.php
on your web server and adjust the settings at the top: $UI_LANGUAGE sets the language for your
visitors (English or German), $TOWN puts results for your town first, $OFFICIAL_ONLY
shows only results from public authorities and courts. Runs on PHP 7.4 or newer, like most web hosts.
Every request costs one search. Keep an eye on your credit (/v1/usage). The page is closed to
search engines (noindex) and allows at most 30 searches per minute ($MAX_PER_MINUTE),
so bots cannot use up your credit. Your visitors' search terms are sent to Polias to answer them.
Please mention this in your privacy policy.
Eine einzige PHP-Datei mit Suchfeld, Trefferliste und „Weitere Treffer“, ohne weitere Bausteine. Gedacht etwa
für Gemeinden, Vereine oder Firmen, die auf ihrer Website eine Suche anbieten wollen. Datei z. B. als
search.php auf den Webserver legen und oben die Einstellungen anpassen: $UI_LANGUAGE
ist die Sprache für Ihre Besucher ('de' für Deutsch), mit $TOWN kommen Treffer für
Ihren Ort zuerst, mit $OFFICIAL_ONLY nur Treffer von Behörden, Gemeinden und Gerichten. Läuft mit
PHP 7.4 oder neuer, wie bei den meisten Webhostern.
Jeder Aufruf der Seite kostet eine Suche. Behalten Sie Ihr Guthaben im Blick (/v1/usage). Die
Seite ist für Suchmaschinen gesperrt (noindex) und lässt höchstens 30 Suchen je Minute zu
($MAX_PER_MINUTE), damit Roboter Ihr Guthaben nicht aufbrauchen. Die Suchbegriffe Ihrer Besucher
werden zur Beantwortung an Polias übermittelt. Bitte erwähnen Sie das in Ihrer Datenschutzerklärung.
Show search page (PHP, about 130 lines)Suchseite anzeigen (PHP, rund 130 Zeilen)
<?php
/*
* Ready-made search page powered by Polias: a single file, PHP 7.4 or newer, no dependencies.
* Put it on your web server (e.g. as search.php) and adjust the settings below.
* Every request with a query costs one search from your Polias credit (check: /v1/usage).
* Your visitors' queries are sent to Polias to answer them: please mention this in your privacy policy.
* License MIT-0, provided without warranty.
*/
// ---- Settings -----------------------------------------------------------------------------------
$API_KEY = getenv('POLIAS_API_KEY') ?: 'pol_YOUR_API_KEY'; // your key
$TITLE = 'Search'; // page heading
$UI_LANGUAGE = 'en'; // language of this page for your visitors: 'en' or 'de'
$INDEX_LANGUAGE = 'de'; // search index: 'de' (German) or 'en' (English, focus on technical topics)
$TOWN = ''; // e.g. 'Freiburg im Breisgau': prefer results for this town (German index only)
$OFFICIAL_ONLY = false; // true: only results from public authorities and courts (German index only)
$PER_PAGE = 10; // results per page, 1 to 10
$MAX_PER_MINUTE = 30; // at most this many searches per minute through this page (protects against bots)
// -------------------------------------------------------------------------------------------------
// Settings from the Polias project builder, if the file is there (it overrides the values above).
if (is_file(__DIR__ . '/polias-config.php')) include __DIR__ . '/polias-config.php';
$TEXT = [
'en' => ['placeholder' => 'Enter a search term', 'button' => 'Search', 'none' => 'No results for “%s”.',
'busy' => 'Too many searches right now. Please try again in a minute.',
'down' => 'Search is not available right now. Please try again later.',
'more' => 'More results →', 'credit' => 'Search results by'],
'de' => ['placeholder' => 'Suchbegriff eingeben', 'button' => 'Suchen', 'none' => 'Keine Treffer für „%s“.',
'busy' => 'Gerade sind zu viele Suchen auf einmal. Bitte in einer Minute noch einmal versuchen.',
'down' => 'Die Suche ist gerade nicht erreichbar. Bitte später noch einmal versuchen.',
'more' => 'Weitere Treffer →', 'credit' => 'Suchergebnisse von'],
][$UI_LANGUAGE] ?? [];
function h($text) { return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8'); }
// Counts the searches of the current minute for the whole page (stores nothing about visitors).
function within_limit(int $limit): bool
{
$file = fopen(sys_get_temp_dir() . '/polias-search-counter', 'c+');
if (!$file) return true;
flock($file, LOCK_EX);
[$minute, $count] = array_map('intval', explode(' ', trim(stream_get_contents($file)) . ' 0 0'));
$now = (int) (time() / 60);
$count = $minute === $now ? $count + 1 : 1;
ftruncate($file, 0);
rewind($file);
fwrite($file, "$now $count");
flock($file, LOCK_UN);
fclose($file);
return $count <= $limit;
}
$query = trim(mb_substr((string) ($_GET['q'] ?? ''), 0, 200));
$offset = max(0, min(90, (int) ($_GET['start'] ?? 0)));
$results = [];
$error = '';
if ($query !== '' && !within_limit($MAX_PER_MINUTE)) {
$error = $TEXT['busy'];
} elseif ($query !== '') {
$params = ['q' => $query, 'count' => $PER_PAGE, 'offset' => $offset, 'lang' => $INDEX_LANGUAGE];
if ($TOWN !== '' && $INDEX_LANGUAGE === 'de') $params['ort'] = $TOWN;
if ($OFFICIAL_ONLY && $INDEX_LANGUAGE === 'de') $params['quelle'] = 'amtlich';
$context = stream_context_create(['http' => [
'header' => "Authorization: Bearer $API_KEY\r\n",
'timeout' => 15,
'ignore_errors' => true,
]]);
$body = @file_get_contents('https://api.polias.eu/v1/search?' . http_build_query($params), false, $context);
$status = isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m) ? (int) $m[1] : 0;
if ($status === 200) {
$results = json_decode($body, true)['results'] ?? [];
} elseif ($status === 429) {
$error = $TEXT['busy'];
} else {
$error = $TEXT['down'];
error_log("Polias search: status $status"); // 401 = wrong key, 402 = credit used up
}
}
?><!doctype html>
<html lang="<?= h($UI_LANGUAGE) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title><?= h($query !== '' ? "$query – $TITLE" : $TITLE) ?></title>
<style>
body { font: 17px/1.5 system-ui, sans-serif; max-width: 760px; margin: 0 auto; padding: 24px 16px; color: #1d1d1b; }
form { display: flex; gap: 8px; margin: 16px 0 24px; }
input[type=search] { flex: 1; font: inherit; padding: 10px 14px; border: 1px solid #bbb; border-radius: 10px; }
button { font: inherit; padding: 10px 18px; border: 0; border-radius: 10px; background: #16241a; color: #fff; cursor: pointer; }
.result { margin: 0 0 22px; }
.result a { font-size: 19px; color: #1a4fa0; text-decoration: none; }
.result a:hover { text-decoration: underline; }
.url { color: #2e6b3a; font-size: 14px; word-break: break-all; }
.snippet { margin: 2px 0 0; color: #444; }
.credit { color: #666; font-size: 14px; }
</style>
</head>
<body>
<h1><?= h($TITLE) ?></h1>
<form method="get" role="search">
<input type="search" name="q" value="<?= h($query) ?>" placeholder="<?= h($TEXT['placeholder']) ?>" maxlength="200" aria-label="<?= h($TEXT['placeholder']) ?>" autofocus>
<button type="submit"><?= h($TEXT['button']) ?></button>
</form>
<?php if ($error !== ''): ?>
<p><?= h($error) ?></p>
<?php elseif ($query !== '' && !$results): ?>
<p><?= h(sprintf($TEXT['none'], $query)) ?></p>
<?php endif; ?>
<?php foreach ($results as $r): if (!preg_match('#^https?://#i', $r['url'] ?? '')) continue; ?>
<div class="result">
<a href="<?= h($r['url']) ?>" rel="noopener"><?= h($r['title']) ?></a>
<div class="url"><?= h($r['url']) ?></div>
<?php if (!empty($r['snippet'])): ?><p class="snippet"><?= h($r['snippet']) ?></p><?php endif; ?>
</div>
<?php endforeach; ?>
<?php if (count($results) === $PER_PAGE && $offset + $PER_PAGE <= 90): ?>
<p><a href="?<?= h(http_build_query(['q' => $query, 'start' => $offset + $PER_PAGE])) ?>" rel="nofollow"><?= h($TEXT['more']) ?></a></p>
<?php endif; ?>
<p class="credit"><?= h($TEXT['credit']) ?> <a href="https://polias.eu">Polias</a></p>
</body>
</html>
QuestionsFragen
Something not working, or missing a template? Write to us at hallo@polias.eu. All parameters are in the developer guide.
Klappt etwas nicht, oder fehlt Ihnen eine Vorlage? Schreiben Sie uns an hallo@polias.eu. Alle Angaben stehen in der Anleitung für Entwickler.