Registry / database / postgrest

postgrest

JSON →
library2.31.0pypypi✓ verified 27d ago

The `postgrest` library provides an ORM-like interface for interacting with PostgREST APIs from Python. It supports both synchronous and asynchronous operations, allowing developers to easily query, insert, update, and delete data, as well as call stored procedures. The library is actively maintained, currently at version 2.28.3, and has a consistent release cadence with frequent updates.

pip install postgrest
INSTALL
IMPORT
SIG · POSTGREST
P
postgrest
databasepythonv2.31.0
Install
5.2s avg
Import
688ms
Disk
34MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.31.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.708s · 35.6MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 5.2s · import 0.668s · 35MB
34MB installed
● package 34MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

AsyncPostgrestClient
from postgrest import AsyncPostgrestClient
The primary asynchronous client for PostgREST interactions.
SyncPostgrestClient
from postgrest import SyncPostgrestClient
The synchronous client for PostgREST interactions, useful in non-async contexts.

This quickstart demonstrates how to initialize an `AsyncPostgrestClient`, perform basic CRUD (Create, Read, Update, Delete) operations, and call `execute()` to send requests. It assumes a running PostgREST server accessible at `POSTGREST_URL` with a 'countries' table. The example also shows how to optionally include authentication headers.

import asyncio import os from postgrest import AsyncPostgrestClient # Replace with your PostgREST URL and (optional) API key POSTGREST_URL = os.environ.get('POSTGREST_URL', 'http://localhost:3000') # BEARER_TOKEN = os.environ.get('POSTGREST_TOKEN', 'YOUR_API_KEY') # Optional, if authentication is required async def main(): # headers = {'Authorization': f'Bearer {BEARER_TOKEN}'} if BEARER_TOKEN else {} headers = {} async with AsyncPostgrestClient(POSTGREST_URL, headers=headers) as client: try: # Example: Insert data print('Inserting a new country...') insert_result = await client.from_('countries').insert({'name': 'Exampleland', 'capital': 'Example City'}).execute() print(f'Insert successful: {insert_result.data}') # Example: Read data print('Fetching countries...') response = await client.from_('countries').select('id', 'name', 'capital').limit(5).execute() print('Fetched countries:') for country in response.data: print(f" ID: {country['id']}, Name: {country['name']}, Capital: {country['capital']}") # Example: Update data print('Updating Exampleland...') update_result = await client.from_('countries').update({'capital': 'New Example City'}).eq('name', 'Exampleland').execute() print(f'Update successful: {update_result.data}') # Example: Delete data print('Deleting Exampleland...') delete_result = await client.from_('countries').delete().eq('name', 'Exampleland').execute() print(f'Delete successful: {delete_result.data}') except Exception as e: print(f"An error occurred: {e}") if __name__ == '__main__': asyncio.run(main())
Debug
Known issues
breakingThe behavior of the `.schema()` method changed in version 1.0.0. It now persists only for the current query builder instance and does not affect subsequent queries on the client or other query builders.
fix
If upgrading from pre-1.0.0, ensure that you explicitly call `.schema()` for each query chain where a specific schema is needed, or instantiate a new client for each schema. Review your codebase for `.schema()` usage patterns.
affects: >=1.0.0
breakingA 'minor breaking change' was noted for users integrating with `supabase_auth` around version 2.24.0. While not directly in the `postgrest` library itself, it indicates potential compatibility issues for Supabase users.
fix
If experiencing issues with `supabase_auth` after upgrading `postgrest` to versions >=2.24.0, consider locking your `postgrest` dependency to a compatible version (e.g., 2.23.x) or consult Supabase documentation for updated integration patterns.
affects: >=2.24.0
gotchaThe library offers both `AsyncPostgrestClient` and `SyncPostgrestClient`. Mixing asynchronous and synchronous code incorrectly (e.g., calling `await` on a `SyncPostgrestClient` method or blocking an event loop with `SyncPostgrestClient` in an async context) will lead to errors or performance issues.
fix
Use `AsyncPostgrestClient` within `async` functions with `await` and `async with`. Use `SyncPostgrestClient` in regular, non-async Python code. Do not mix them directly without proper async bridge patterns (e.g., `asyncio.to_thread` for sync calls in async code).
affects: All versions
gotchaResponses from `execute()` contain the data in the `.data` attribute. Direct access to the response object might not yield the expected results if not correctly parsing the structure.
fix
Always access the query results via `response.data` after a successful `execute()` call. Implement proper error handling (e.g., `try...except` blocks) to catch `PostgrestAPIError` or other exceptions raised by failed requests.
affects: All versions
gotchaConnection attempts may fail if the provided `POSTGREST_URL` is incorrect, unreachable, or if the PostgREST server is not running or accessible from the client's network environment. This often manifests as 'All connection attempts failed' or similar network errors.
fix
Verify that the `POSTGREST_URL` used to initialize the client (e.g., `AsyncPostgrestClient` or `SyncPostgrestClient`) is correct and points to a valid, running, and publicly accessible PostgREST instance. Check network connectivity, firewall rules, and ensure the PostgREST server is operational and listening on the specified port.
affects: All versions
gotchaConnection to the Postgrest server failed. This can be caused by an incorrect host or port in the client URL, the server being unreachable (e.g., firewall, server not running), or general network issues preventing communication.
fix
Verify the `url` and any necessary connection `headers` (e.g., `apikey`) provided to the `PostgrestClient` constructor. Ensure the Postgrest server is running and accessible from where the client code is executed (check network connectivity, firewall rules, and server status).
affects: All versions
Errors
Common errors & fixes
OperationalError: FATAL: password authentication failed for user "..."
The Python client failed to authenticate with the PostgreSQL database, usually due to incorrect username, password, host, or port, or the database server not running or not configured to accept connections from the client's host.
fix
Verify that your `url` and `headers` (if using JWT) parameters are correct, including the database host, port, username, and password. Ensure the PostgREST server (and underlying PostgreSQL database) is running and accessible from where the Python client is executed. Check PostgreSQL's `pg_hba.conf` for client authentication rules.
AttributeError: 'list' object has no attribute 'json'
The `execute()` method in `postgrest-py` returns an `APIResponse` object, which contains the data as a list of dictionaries in its `data` attribute. This error occurs when attempting to call `.json()` directly on the `data` attribute (which is already a list) instead of accessing its contents.
fix
Access the `data` attribute of the `APIResponse` object directly to get the list of dictionaries. If you expect a single row, use `.single().execute()` to get a dictionary, or access the first element of the list `response.data[0]`. 

```python
from postgrest import PostgrestClient

async def fetch_data(client: PostgrestClient):
    response = await client.from_("mytable").select("*").execute()
    # Correct way to access the data:
    records = response.data # records is a list of dictionaries
    print(records)
    # If expecting a single record and using .single():
    # single_record_response = await client.from_("mytable").select("*").eq("id", 1).single().execute()
    # record = single_record_response.data # record is a dictionary
    # print(record)
```
ModuleNotFoundError: No module named 'postgrest'
The `postgrest` Python library, or its official client `postgrest-py`, is not installed in the current Python environment or the import statement is incorrect.
fix
Install the `postgrest-py` package using pip:

```bash
pip install postgrest-py
```

Ensure you are installing it into the correct Python environment (e.g., your virtual environment) and that your script is running with that environment's Python interpreter. If you are importing `postgrest`, ensure the package name is correct in your `import` statement.
postgrest.exceptions.APIError: {'code': 'PGRST...', 'message': '...'}
This error indicates an issue on the PostgREST server side, such as a malformed API request, a non-existent table or function, or a database error passed through by PostgREST. The 'code' and 'message' fields in the error dictionary provide more specific details from the PostgREST server. For example, 'PGRST202' indicates 'Could not find the api.function() function in the schema cache'.
fix
Examine the `code` and `message` within the `APIError` to understand the specific problem. Common fixes include: 
*   Correcting the table or function name in your query. 
*   Ensuring the PostgREST server's schema cache is up-to-date (which might require a server restart if the database schema changed). 
*   Checking the PostgREST server logs for more detailed error information. 
*   Verifying that the request body for insert/update operations is valid JSON and matches the table schema.
TypeError: 'SelectBuilder' object is not callable
This error typically occurs when a developer attempts to call an intermediate query builder object (like `SelectBuilder` or another chainable method result) as if it were a function, instead of continuing to chain methods or calling a terminal execution method like `.execute()`.
fix
Ensure that you are correctly chaining methods in your query and terminating with an execution method. For instance, if you intend to execute a query, you must call `.execute()` at the end of the chain. 

```python
from postgrest import PostgrestClient

async def query_users(client: PostgrestClient):
    # Incorrect: Trying to call the select object
    # users = await client.from_("users").select("*")()

    # Correct: Chain methods and call .execute()
    users_response = await client.from_("users").select("*").eq("status", "active").order("id").execute()
    active_users = users_response.data
    print(active_users)
```
Upgrade
Version history
2.31.0latest on PyPI · released Jun 4, 2026
Audit
Dependencies
httpxrequiredHTTP client for making requests to PostgREST.
deprecationrequiredUsed for handling deprecated features.
pydanticrequiredUsed for data validation and modeling.
strenumrequiredProvides StrEnum for Python versions <3.11.
Agent activity
17 hits · last 30 days
node
14
Amazon
1
Resources
postgrest — pip install postgrest · libregistry