PostGIS and GeoJSON

Copy Markdown View Source

PgRest serves application/geo+json on databases that have PostGIS, and renders spatial columns in ordinary JSON exactly as PostgREST does. Every statement below was recorded against the pinned PostgREST v14.18 on PostGIS 3.3.7 by the differential suite (test/compat/expected/geojson.json, geo_plain_json.json, search_path.json). Spatial filter operators are not supported (see Not yet supported).

The examples use neutral names: a places table with a location point, and parcels.

geo+json

Send Accept: application/geo+json. PgRest answers a GeoJSON FeatureCollection built by PostGIS' ST_AsGeoJSON(record), with Content-Type: application/geo+json; charset=utf-8. There is nothing to configure: PgRest reads whether PostGIS is installed once per repo, and the PostGIS schema is taken from the catalog (Supabase installs it in extensions). The facts are cached (persistent_term) until PgRest.Catalog.forget/1 or a restart, so installing PostGIS after boot keeps answering 406 until then.

GET /places?order=id
Accept: application/geo+json
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {"type": "Point", "coordinates": [-97.74, 30.27]},
      "properties": {"id": 1, "name": "north"}
    }
  ]
}

supabase-js sets this header with .geojson().

What becomes the feature geometry

PostGIS decides, not PgRest: the first spatial column of the projected row is the feature geometry, and every other column is a property.

RowResult
geometry columnthe feature geometry, left out of properties
geography columnqualifies as the feature geometry
geography column and a later geometry columnthe geography column is the feature geometry, the other is a property
two geometry columnsthe first selected one is the feature geometry (select= order decides)
every spatial column cast to text (location::text)400 22023 "geometry column is missing"
domain over geographynot recognised: 400 22023 "geometry column is missing"
SQL NULL geometrya feature whose geometry is {"type": null}; nulls=stripped has no effect
geometry with a non-4326 SRIDthe member carries a crs object (EPSG:3857); SRID 4326 and SRID 0 do not
POINT Mthe M value is dropped
POINT EMPTYcoordinates: []
invalid polygon (a bowtie)passed through unchanged
curve types (CIRCULARSTRING)500 XX000 "lwgeom_to_geojson: 'CircularString' geometry type not supported"

Property names follow select= aliases, as in JSON. Spatial columns that are not the feature geometry appear in properties as in plain JSON: a geometry as a GeoJSON object (with a crs member), a geography as hex EWKB text.

Embeds, spreads and the shape of the rest

  • Embeds are nested properties in the shape plain JSON gives them (a to-one embed an object, a to-many embed an array), never nested FeatureCollections. Spread embeds hoist their columns into properties, to-one and to-many alike; an ordered to-many spread adds no helper column to the properties.
  • RPC works on functions returning setof a table (one feature per row) and on a function returning a spatial scalar (one feature with empty properties). A function returning a non-spatial scalar is a 400 22023.
  • Writes with Prefer: return=representation (POST, PATCH, PUT, DELETE) answer the FeatureCollection of the returned rows. return=minimal has an empty body. An insert answers Content-Range: */*, a PUT has no Content-Range, and deleting a place that a point still references is a 409 23503.
  • HEAD answers with the headers of the GET, including the geo Content-Type, and no body. It runs no GeoJSON aggregate, so it never fails on a geometry that the aggregate cannot render.
  • Status, Content-Range, Prefer: count=..., Range, limit, offset and Accept-Profile behave as for JSON. Accept: application/json;q=0.5, application/geo+json picks geo+json, application/geo+json;q=0.1, application/json picks JSON.
  • application/vnd.pgrst.object+json semantics do not apply: geo+json is always a collection.
  • application/vnd.pgrst.plan with for="application/geo+json" is served on PostGIS databases (it needs plan_enabled as usual), also for a resource without a spatial column.
  • A request that reads a resource with after_load/2 is never offered geo+json: a client that also accepts JSON gets JSON, any other a 406 PGRST107.

Geometries are large: there is no limit beyond max_limit, statement_timeout and max_body_bytes, so paginate (limit, Range) when a table holds big polygons.

GeoJSON in ordinary JSON

PgRest adds no rendering option for this. The PostgREST-native idioms work, and each is proven against PostgREST:

  1. A geometry column is a GeoJSON object in plain JSON, at the root and in embeds, with a crs member ("crs": {"type": "name", "properties": {"name": "EPSG:4326"}}).
  2. A geography column is hex EWKB text in plain JSON (PostGIS has no geography to json cast).
  3. A select cast of a geography column to geometry returns GeoJSON: ?select=id,center::geometry. It works at the root, in an embed (?select=id,places(center::geometry)) and in a spread (?select=id,...places(center::geometry)). On Supabase the same cast works directly with PostGIS in extensions (geo_plain_json/supabase-cast). The unqualified geometry resolves through the request search_path; with PostGIS outside public set extra_search_path (below).
  4. A view that does the cast, which works without any search path setting, also on Supabase as a security_invoker view over extensions.geometry (geo_plain_json/view-*, geo_plain_json/supabase-view):
CREATE VIEW public.landmarks_geojson WITH (security_invoker = true) AS
  SELECT id, name, position::extensions.geometry AS position
  FROM public.landmarks;

Register the view as an ordinary resource. security_invoker = true (PostgreSQL 15 or later) keeps the base table's grants and row level security in force for the caller; without it the view runs as its owner and can widen what a caller reads. The Supabase test fixture grants USAGE on the extensions schema to the API roles.

A NULL spatial column is null in plain JSON.

Search path for extension types

PostgREST's db-extra-search-path is the plug option extra_search_path:

forward "/api", PgRest.Plug,
  repo: MyApp.Repo,
  extra_search_path: ["public", "extensions"]

The request search_path is the function schema (for RPC), then the schema of every resource the request touches, then extra_search_path. The option only extends the search_path; it never exposes tables or functions of those schemas (a request for an extension table such as spatial_ref_sys is a 404 PGRST205). The default is ["public"].

The value must be a non-empty list of distinct, non-empty strings without NUL bytes; anything else, including [], raises ArgumentError at PgRest.Plug.init/1. PostgREST accepts an empty db-extra-search-path; PgRest does not, and the list replaces the default, so ["extensions"] leaves public out of the extra part (a resource in public still puts public on the path). geo+json itself does not need this option, because ST_AsGeoJSON is schema-qualified from the catalog.

Without PostGIS

On a database without PostGIS, application/geo+json is a 406 PGRST107. PostgREST fails there with a 404 42883 (undefined function st_asgeojson). This is a labeled difference listed in the Compatibility guide.

Not yet supported

Spatial filter operators (distance, intersects, bounding box) are not part of PostgREST either. Use an RPC function (places_within(geojson jsonb) returning setof places), which also works with geo+json output, a view for a fixed predicate, or a membership table filtered with ordinary operators and embeds.