PostgREST
PostgREST (pronounced "post-gress-t")
Automatically exposes PostgreSQL as a RESTful API. Schema-based API.
PostgREST (pronounced "post-gress-t")
Automatically exposes PostgreSQL as a RESTful API. Schema-based API.
PostgREST is a standalone web server that automatically converts a PostgreSQL database into a RESTful API. Without any separate backend code, it exposes database tables, views, and functions as HTTP endpoints so that CRUD operations can be performed. It takes a "schema-first" approach, in which the database schema itself becomes the API specification.
PostgREST supports authentication/authorization using PostgreSQL's Row Level Security (RLS). By mapping the claims of a JWT token to PostgreSQL roles, row-level access control is possible at the database level. This is more secure because security is enforced in the database rather than in application logic.
API requests can be filtered, sorted, paginated, and have their columns selected through URL parameters. It supports query syntax such as `?select=id,name`, `?order=created_at.desc`, and `?limit=10&offset=20`, and by embedding relational data, joined data can also be retrieved in a single request.
Supabase uses PostgREST as a core component to provide a "Firebase alternative." It is a complete BaaS (Backend as a Service) that adds real-time subscriptions, authentication, storage, and more to PostgREST. It can greatly save backend development time when building prototypes quickly or simple CRUD apps.
-- === PostgreSQL μ€ν€λ§ μ μ ===
-- ν
μ΄λΈ μμ±
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
category VARCHAR(100),
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE reviews (
id SERIAL PRIMARY KEY,
product_id INT REFERENCES products(id),
user_id INT,
rating INT CHECK (rating >= 1 AND rating <= 5),
comment TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
-- Row Level Security νμ±ν
ALTER TABLE products ENABLE ROW LEVEL SECURITY;
ALTER TABLE reviews ENABLE ROW LEVEL SECURITY;
-- μ½κΈ° μ μ±
: λͺ¨λ μ¬μ©μκ° μ½κΈ° κ°λ₯
CREATE POLICY "Products are viewable by everyone"
ON products FOR SELECT
USING (true);
-- μ°κΈ° μ μ±
: μΈμ¦λ μ¬μ©μλ§ λ¦¬λ·° μμ± κ°λ₯
CREATE POLICY "Users can insert their own reviews"
ON reviews FOR INSERT
WITH CHECK (auth.uid() = user_id);
-- APIλ₯Ό μν λ·° μμ±
CREATE VIEW product_with_rating AS
SELECT
p.*,
COALESCE(AVG(r.rating), 0) AS avg_rating,
COUNT(r.id) AS review_count
FROM products p
LEFT JOIN reviews r ON p.id = r.product_id
GROUP BY p.id;
// === JavaScript/TypeScript ν΄λΌμ΄μΈνΈ μ¬μ© μμ ===
// κΈ°λ³Έ CRUD μμ
const API_URL = 'https://your-project.supabase.co/rest/v1';
const API_KEY = 'your-anon-key';
const headers = {
'apikey': API_KEY,
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
'Prefer': 'return=representation' // INSERT/UPDATE ν κ²°κ³Ό λ°ν
};
// GET - μ 체 μν μ‘°ν
const getAllProducts = async () => {
const response = await fetch(`${API_URL}/products`, { headers });
return response.json();
};
// GET - νν°λ§, μ λ ¬, νμ΄μ§λ€μ΄μ
const getFilteredProducts = async () => {
const params = new URLSearchParams({
'select': 'id,name,price,category', // μ»¬λΌ μ ν
'category': 'eq.electronics', // νν°: category = 'electronics'
'price': 'lte.1000', // νν°: price <= 1000
'order': 'price.asc', // μ λ ¬: κ°κ²© μ€λ¦μ°¨μ
'limit': '10', // νμ΄μ§ ν¬κΈ°
'offset': '0' // μμ μμΉ
});
const response = await fetch(`${API_URL}/products?${params}`, { headers });
return response.json();
};
// GET - κ΄κ³ λ°μ΄ν° μλ² λ© (JOIN)
const getProductsWithReviews = async () => {
// μνκ³Ό ν¨κ» 리뷰λ κ°μ Έμ€κΈ°
const response = await fetch(
`${API_URL}/products?select=*,reviews(*)`,
{ headers }
);
return response.json();
};
// GET - λ·° μ‘°ν (νκ· νμ ν¬ν¨)
const getProductsWithRating = async () => {
const response = await fetch(
`${API_URL}/product_with_rating?order=avg_rating.desc`,
{ headers }
);
return response.json();
};
// POST - μν μΆκ°
const createProduct = async (product: {
name: string;
price: number;
category: string;
}) => {
const response = await fetch(`${API_URL}/products`, {
method: 'POST',
headers,
body: JSON.stringify(product)
});
return response.json();
};
// PATCH - μν μμ
const updateProduct = async (id: number, updates: Partial<Product>) => {
const response = await fetch(`${API_URL}/products?id=eq.${id}`, {
method: 'PATCH',
headers,
body: JSON.stringify(updates)
});
return response.json();
};
// DELETE - μν μμ
const deleteProduct = async (id: number) => {
await fetch(`${API_URL}/products?id=eq.${id}`, {
method: 'DELETE',
headers
});
};
// === Supabase JavaScript ν΄λΌμ΄μΈνΈ (λ κ°νΈν λ°©μ) ===
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
'https://your-project.supabase.co',
'your-anon-key'
);
// λμΌν μμ
μ λ κ°νΈνκ²
const { data, error } = await supabase
.from('products')
.select('*, reviews(*)')
.eq('category', 'electronics')
.lte('price', 1000)
.order('price', { ascending: true })
.range(0, 9);
// μ€μκ° κ΅¬λ
const subscription = supabase
.channel('products-changes')
.on('postgres_changes',
{ event: '*', schema: 'public', table: 'products' },
(payload) => {
console.log('λ³κ²½ κ°μ§:', payload);
}
)
.subscribe();
"I need to build a prototype quickly without a backend developer. What should I do?"
"You can use Supabase or PostgREST. If you just define tables in PostgreSQL, a REST API is generated automatically. Not only CRUD but also filtering, pagination, and JOINs can be handled with URL parameters, so you can implement features with just the frontend, without any separate backend code."
"How do you handle security when you build an API with PostgREST?"
"You use PostgreSQL's Row Level Security (RLS). If you define a policy at the database level such as 'only this user can access this row,' PostgREST parses the JWT token and runs the query with the corresponding role. Since security is enforced in the DB rather than the application, it's more secure."
"What are the limitations of PostgREST?"
"There are limitations when complex business logic or external API integration is required. Work beyond simple CRUD needs to be implemented as PostgreSQL functions or requires a separate service. Also, since a schema change is an API change, you need to be careful about version control and maintaining backward compatibility."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
RLS required: When using PostgREST in production, be sure to enable Row Level Security. If you expose it without RLS, anyone can access all data. You must define appropriate SELECT, INSERT, UPDATE, and DELETE policies for each table.
Schema exposure: PostgREST exposes the database schema as an API as it is. Separate sensitive columns or tables into a different schema, or use views to expose only the necessary columns. By default, only the public schema is exposed.
Complex logic: Complex tasks requiring transactions, external service integration, asynchronous tasks, and the like need PostgreSQL functions or a separate backend. PostgREST is optimized for simple, CRUD-centered APIs.