Prompt
search api for postgres data
Latest observation
Oct 12, 2026
OpenAI APIWeb search: off
If you want to search data in PostgreSQL via an API, the usual pattern is:
1) Create a backend API endpoint
Your API receives search parameters, queries Postgres, and returns JSON.
Example (Node.js + Express + pg)
import express from "express";
import { Pool } from "pg";
const app = express();
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
app.get("/api/search", async (req, res) => {
const q = req.query.q || "";
try {
const result = await pool.query(
`SELECT id, name, description
FROM items
WHERE name ILIKE $1 OR description ILIKE $1
ORDER BY id DESC
LIMIT 50`,
[`%${q}%`]
);
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Search failed" });
}
});
app.listen(3000, () => console.log("Server running on port 3000"));
2) Search with Postgres full-text search
For better search quality than ILIKE, use PostgreSQL full-text search.
Example query
SELECT id, title, body
FROM documents
WHERE to_tsvector('english', title || ' ' || body)
@@ plainto_tsquery('english', 'your search text');
Better API example
app.get("/api/search", async (req, res) => {
const q = req.query.q || "";
try {
const result = await pool.query(
`SELECT id, title, body,
ts_rank(to_tsvector('english', title || ' ' || body),
plainto_tsquery('english', $1)) AS rank
FROM documents
WHERE to_tsvector('english', title || ' ' || body)
@@ plainto_tsquery('english', $1)
ORDER BY rank DESC
LIMIT 20`,
[q]
);
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: "Search failed" });
}
});
3) Add indexes for performance
For full-text search:
CREATE INDEX documents_search_idx
ON documents
USING GIN (to_tsvector('english', title || ' ' || body));
4) If you want a ready-made API
You can also expose Postgres through:
- PostgREST
- Hasura
- Supabase
- Prisma + your own API
- GraphQL APIs
5) Important security tips
- Use parameterized queries (prevents SQL injection)
- Validate user input
- Add pagination (
LIMIT/OFFSETor cursor pagination) - Restrict fields returned
If you want, I can give you:
- a Python/FastAPI version,
- a PostgreSQL full-text search setup, or
- a ready-made API using PostgREST/Hasura.