A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgres-postgrest.php below:

Website Navigation


Integrating PostgREST with PostgreSQL for RESTful APIs

Integrating PostgREST with PostgreSQL for RESTful APIsLast update on December 31 2024 05:34:51 (UTC/GMT +8 hours)

PostgreSQL and PostgREST: A Detailed Guide

PostgREST is an open-source tool that provides a RESTful API for any PostgreSQL database. It automatically generates endpoints for your database schema, allowing you to interact with your PostgreSQL data over HTTP. This eliminates the need for building custom backends for simple database access, enhancing productivity and reducing complexity.

This guide covers the basics of PostgREST, its configuration, how it interacts with PostgreSQL, and examples of using it to create a RESTful API for database operations.

Syntax:

PostgREST doesn’t have traditional syntax but relies on a configuration file (postgrest.conf) to connect to a PostgreSQL database. Below is an example configuration:

db-uri = postgres://user:password@localhost:5432/mydb
db-schema = public
db-anon-role = web_anon
server-port = 3000

Steps to Use PostgREST with PostgreSQL

Examples:

1. Setting up a PostgreSQL Database

Create a simple tasks table for demonstration:

Code:


-- Create a tasks table
CREATE TABLE tasks (
    id SERIAL PRIMARY KEY, -- Auto-incrementing primary key
    title TEXT NOT NULL,   -- Task title
    status BOOLEAN DEFAULT FALSE -- Task completion status
);

-- Grant access to a role
CREATE ROLE web_anon; -- Create a role for anonymous access
GRANT USAGE ON SCHEMA public TO web_anon; -- Grant schema usage
GRANT SELECT ON ALL TABLES IN SCHEMA public TO web_anon; -- Allow read-only access

2. PostgREST Configuration

Save the following as postgrest.conf:

Code:


db-uri = postgres://user:password@localhost:5432/mydb -- Connection string
db-schema = public -- Expose only the public schema
db-anon-role = web_anon -- Anonymous access role
server-port = 3000 -- API server port

3. Running PostgREST

Run PostgREST using Docker:

Code:


docker run -p 3000:3000 \
  -v /path/to/postgrest.conf:/etc/postgrest.conf \
  postgrest/postgrest

4. Testing API Endpoints

Retrieve tasks using curl:

Code:


curl http://localhost:3000/tasks

Expected Output (JSON):

[
  { "id": 1, "title": "Learn PostgreSQL", "status": false },
  { "id": 2, "title": "Explore PostgREST", "status": true }
]

Explanation:

Benefits of PostgREST

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4