JSON API

Datasette provides a JSON API for your SQLite databases. Anything you can do through the Datasette user interface can also be accessed as JSON via the API.

To access the API for a page, either click on the .json link on that page or edit the URL and add a .json extension to it.

API stability

Datasette 1.0 makes a stability promise for its JSON API: the endpoints, parameters and response keys documented here and on the pages this documentation links to will not change in backwards-incompatible ways for the duration of the 1.x release series.

Stability means:

  • Documented endpoints will keep their URLs, methods, parameters and permission requirements.

  • Documented response keys will keep their names and types. New keys may be added in any release - clients should ignore keys they do not recognize.

  • The documented ?_extra= names, ?_shape= values and column filter operators are stable.

  • Pagination tokens - the "next" key and ?_next= parameter - are opaque strings. Pass them back exactly as you received them; their internal structure is not part of the API and can change at any time.

  • The standard error format and the API token format and restriction semantics are stable, including the action abbreviations stored inside signed tokens.

Some JSON endpoints are exempt from this promise:

  • Endpoints that are not documented include this marker key in their responses and can change at any time:

    "unstable": "This API is not part of Datasette's stable interface and may change at any time"
    

    This currently covers the instance homepage (/.json), the stored query analyze/store/definition endpoints, /-/query/parameters, /-/execute-write/analyze and the JSON returned by the /-/permissions debug playground.

  • Debug and support endpoints are documented so you can use them, but their JSON shapes are not frozen: /-/threads, /-/tasks, /-/actions, the permission debug endpoints (/-/allowed, /-/rules, /-/check) and the table autocomplete endpoint.

  • Response keys explicitly labeled as unstable in this documentation, such as the "analysis" block returned by execute-write and the debug and request extras.

Default representation

The default JSON representation of data from a SQLite table or custom query looks like this:

{
  "ok": true,
  "rows": [
    {
      "id": 3,
      "name": "Detroit"
    },
    {
      "id": 2,
      "name": "Los Angeles"
    },
    {
      "id": 4,
      "name": "Memnonia"
    },
    {
      "id": 1,
      "name": "San Francisco"
    }
  ],
  "truncated": false
}

"ok" is always true if an error did not occur. Every Datasette JSON endpoint that returns an object includes this key on success.

The "rows" key is a list of objects, each one representing a row.

The "truncated" key lets you know if the query was truncated. This can happen if a SQL query returns more than 1,000 results (or the max_returned_rows setting). Query responses also return this as a Datasette-Truncated: true or Datasette-Truncated: false HTTP header, in JSON and in every other format - see Truncated query results.

For table pages, two additional keys are present: "next", an opaque token that can be used to retrieve the next page using ?_next=TOKEN, and "next_url", the full URL of that next page. Both are null on the final page. See Pagination.

Error responses

Every JSON error response from Datasette uses the same format:

{
    "ok": false,
    "error": "Table not found",
    "errors": [
        "Table not found"
    ],
    "status": 404
}
  • "ok" is always false for an error.

  • "errors" is a list of one or more error message strings. Endpoints that validate multiple things at once - such as the insert API - may return several messages here.

  • "error" is all of those messages joined with "; ", for convenience when displaying a single string.

  • "status" matches the HTTP status code of the response.

Some endpoints add extra context keys. For example, a SQL error from a custom query also includes the empty "rows" and "truncated" keys of the response it was unable to produce.

Errors handled by Datasette's exception and permission handlers use this format when the URL ends in .json or the request sends an Accept: application/json or Content-Type: application/json header. Without one of these signals, an error on an HTML page is rendered as HTML. Errors on explicit .csv URLs remain plain text, regardless of headers.

Executing custom SQL

Actors with the execute-sql permission can execute read-only SQL against a database using /-/query.json:

GET /<database>/-/query.json?sql=select+*+from+dogs

Values for named SQL parameters can be provided as additional query string parameters:

GET /<database>/-/query.json?sql=select+*+from+dogs+where+name=:name&name=Cleo

The response uses the same default representation described above.

Rows

Every row in a table has its own JSON URL, see Row. The row is returned as an object in the "row" key:

GET /fixtures/simple_primary_key/1.json
{
  "ok": true,
  "database": "fixtures",
  "table": "simple_primary_key",
  "primary_keys": ["id"],
  "primary_key_values": ["1"],
  "query_ms": 1.2,
  "row": {
    "id": 1,
    "content": "hello"
  }
}

Pass any ?_shape= option to return the row using the same shapes as table JSON instead. ?_shape=objects returns the table default representation, with the row as the only item in the "rows" list.

Different shapes

The _shape parameter can be used to access alternative formats for the rows key which may be more convenient for your application. There are three options:

  • ?_shape=objects - "rows" is a list of JSON key/value objects - the default for tables and queries

  • ?_shape=arrays - "rows" is a list of lists, where the order of values in each list matches the order of the columns

  • ?_shape=array - a JSON array of objects - effectively just the "rows" key from the default representation

  • ?_shape=array&_nl=on - a newline-separated list of JSON objects

  • ?_shape=arrayfirst - a flat JSON array containing just the first value from each row

  • ?_shape=object - a JSON object keyed using the primary keys of the rows

_shape=arrays looks like this:

{
  "ok": true,
  "next": null,
  "next_url": null,
  "rows": [
    [3, "Detroit"],
    [2, "Los Angeles"],
    [4, "Memnonia"],
    [1, "San Francisco"]
  ]
}

_shape=array looks like this:

[
  {
    "id": 3,
    "name": "Detroit"
  },
  {
    "id": 2,
    "name": "Los Angeles"
  },
  {
    "id": 4,
    "name": "Memnonia"
  },
  {
    "id": 1,
    "name": "San Francisco"
  }
]

_shape=array&_nl=on looks like this:

{"id": 1, "value": "Myoporum laetum :: Myoporum"}
{"id": 2, "value": "Metrosideros excelsa :: New Zealand Xmas Tree"}
{"id": 3, "value": "Pinus radiata :: Monterey Pine"}

_shape=arrayfirst looks like this:

[1, 2, 3]

_shape=object looks like this:

{
  "1": {
    "id": 1,
    "value": "Myoporum laetum :: Myoporum"
  },
  "2": {
    "id": 2,
    "value": "Metrosideros excelsa :: New Zealand Xmas Tree"
  },
  "3": {
    "id": 3,
    "value": "Pinus radiata :: Monterey Pine"
  }
]

The object shape is only available for queries against tables - custom SQL queries and views do not have an obvious primary key so cannot be returned using this format.

The object keys are always strings. If your table has a compound primary key, the object keys will be a comma-separated string.

Pagination

The default JSON representation includes a "next_url" key which can be used to access the next page of results. If that key is null or missing then it means you have reached the final page of results.

Other representations include pagination information in the link HTTP header. That header will look something like this:

link: <https://latest.datasette.io/fixtures/sortable.json?_next=d%2Cv>; rel="next"

Here is an example Python function built using requests that returns a list of all of the paginated items from one of these API endpoints:

def paginate(url):
    items = []
    while url:
        response = requests.get(url)
        try:
            url = response.links.get("next").get("url")
        except AttributeError:
            url = None
        items.extend(response.json())
    return items

Special JSON arguments

Boolean query string arguments - such as ?_labels= and ?_json_infinity= - accept on, true or 1 for true and off, false or 0 for false.

Every Datasette endpoint that can return JSON also accepts the following query string arguments:

?_shape=SHAPE

The shape of the JSON to return, documented above.

?_nl=on

When used with ?_shape=array produces newline-delimited JSON objects.

?_pretty=1

Indents the JSON with two spaces so it is easier to read. This applies to the JSON for tables, rows and SQL queries. It has no effect when combined with ?_shape=array&_nl=on.

?_json=COLUMN1&_json=COLUMN2

If any of your SQLite columns contain JSON values, you can use one or more _json= parameters to request that those columns be returned as regular JSON. Without this argument those columns will be returned as JSON objects that have been double-encoded into a JSON string value.

With _shape=object, the object keys still use the original database primary-key values, even when a primary-key column is decoded using _json.

Compare this query without the argument to this query using the argument

?_json_infinity=on

If your data contains infinity or -infinity values, Datasette will replace them with None when returning them as JSON. If you pass _json_infinity=1 Datasette will instead return them as Infinity or -Infinity which is invalid JSON but can be processed by some custom JSON parsers.

?_timelimit=MS

Sets a custom time limit for the query in ms. You can use this for optimistic queries where you would like Datasette to give up if the query takes too long, for example if you want to implement autocomplete search but only if it can be executed in less than 10ms. This can only shorten the time limit: a value higher than the sql_time_limit_ms setting is reduced to that setting.

?_ttl=SECONDS

For how many seconds should this response be cached by HTTP proxies? Use ?_ttl=0 to disable HTTP caching entirely for this request.

?_trace=1

Turns on tracing for this page: SQL queries executed during the request will be gathered and included in the response, either in a new "_traces" key for JSON responses or at the bottom of the page if the response is in HTML.

The structure of the data returned here should be considered highly unstable and very likely to change.

Only available if the trace_debug setting is enabled.

Expanding JSON responses

Table, row and query JSON responses can be expanded with one or more ?_extra= parameters. These can be repeated or comma-separated:

?_extra=columns&_extra=count,count_sql

Requesting an _extra name that does not exist returns a 400 error in the standard error format, for example {"ok": false, "error": "Unknown _extra: nope", ...}.

Table JSON responses

The available table extras are listed below.

count

Total count of rows matching these filters (May execute additional queries.)

GET /fixtures/facetable.json?_extra=count

15
count_truncated

True if the count hit Datasette's counting limit, meaning the real number of matching rows is at least the reported count. (May execute additional queries.)

GET /fixtures/facetable.json?_extra=count,count_truncated

false
count_sql

SQL query string used to calculate the total count for the current table view, including active filters.

GET /fixtures/facetable.json?_size=0&_extra=count_sql

"select count(*) from facetable "
facet_results

Results of facets calculated against this data. A dictionary with results and timed_out keys: results maps facet names to facet dictionaries with name, type, results and URL keys, and each facet result item includes value, label, count and toggle_url. (May execute additional queries. See Facets for details of how facets work.)

Shape abbreviated from /fixtures/facetable.json?_facet=state&_extra=facet_results.

{
  "results": {
    "state": {
      "name": "state",
      "type": "column",
      "results": [
        {
          "value": "CA",
          "label": "CA",
          "count": 10
        },
        {
          "value": "MI",
          "label": "MI",
          "count": 4
        }
      ]
    }
  },
  "timed_out": []
}
facets_timed_out

List of names of facet calculations that exceeded the facet time limit.

GET /fixtures/facetable.json?_facet=state&_extra=facets_timed_out

A list of the names of any facets that exceeded the facet_time_limit_ms time limit - an empty list if every facet calculation completed.

[]
suggested_facets

Suggestions for facets that might return interesting results. Each item is a dictionary with name and toggle_url keys, and may include extra keys such as type or label depending on the facet class. (May execute additional queries. Suggestions are controlled by the suggest_facets setting.)

Shape abbreviated from /fixtures/facetable.json?_extra=suggested_facets.

[
  {
    "name": "state",
    "toggle_url": "http://localhost/fixtures/facetable.json?_extra=suggested_facets&_facet=state"
  }
]
human_description_en

Human-readable description of the filters

GET /fixtures/facetable.json?state=CA&_sort=pk&_extra=human_description_en

"where state = \"CA\" sorted by pk"
columns

List of column names returned by this table, row or query.

GET /fixtures/facetable.json?_extra=columns

[
  "pk",
  "created",
  "planet_int",
  "on_earth",
  "state",
  "_city_id",
  "_neighborhood",
  "tags",
  "complex_array",
  "distinct_some_null",
  "n"
]
all_columns

List of all column names in the table, regardless of _col= or _nocol= filtering.

GET /fixtures/facetable.json?_col=pk&_extra=all_columns

[
  "pk",
  "created",
  "planet_int",
  "on_earth",
  "state",
  "_city_id",
  "_neighborhood",
  "tags",
  "complex_array",
  "distinct_some_null",
  "n"
]
primary_keys

List of primary key column names for this table, or an empty list if the table has no explicit primary key.

GET /fixtures/facetable.json?_extra=primary_keys

[
  "pk"
]
row_paths

The path of each row in rows, in the same order: the part of its row page URL after the table, such as 3 for /fixtures/facetable/3. A path is the row's primary key values, tilde-encoded and joined with commas, or its rowid for a table with no primary key, and null for a row with a null primary key, which has no row page. The whole extra is null for views.

GET /fixtures/compound_primary_key.json?_extra=row_paths

[
  "a,b",
  "a~2Fb,~2Ec-d",
  "d,e"
]
column_details

SQLite schema details for columns in this table. The dictionary maps column names to objects describing the schema for each column. (Each object has type as the declared type string returned by SQLite, or "" if no type was declared; sqlite_type as the normalized SQLite affinity, one of TEXT, INTEGER, REAL, BLOB or NUMERIC; notnull as a boolean; default as the raw SQL default expression string, such as "42", "'hello'" or "datetime('now')", or null if there is no default; is_pk as a boolean; pk_position as the integer primary key position reported by SQLite, or 0 for columns that are not part of the primary key; and hidden as the integer value reported by SQLite's PRAGMA table_xinfo. hidden is 0 for normal columns, 1 for hidden virtual table columns, 2 for virtual generated columns and 3 for stored generated columns.)

GET /fixtures/binary_data.json?_size=0&_extra=column_details

{
  "data": {
    "type": "BLOB",
    "sqlite_type": "BLOB",
    "notnull": false,
    "default": null,
    "is_pk": false,
    "pk_position": 0,
    "hidden": 0
  }
}
display_columns

Column metadata used by the HTML table display. Each item includes name, sortable, is_pk, type, notnull, description, column_type, column_type_config and has_fks keys. has_fks is true when at least one cell in the column is displayed as a link to a foreign key row.

Shape abbreviated from /fixtures/facetable.json?_size=1&_extra=display_columns.

[
  {
    "name": "pk",
    "sortable": true,
    "is_pk": true,
    "type": "INTEGER",
    "notnull": 0
  },
  {
    "name": "created",
    "sortable": true,
    "is_pk": false,
    "type": "TEXT",
    "notnull": 0,
    "description": null,
    "column_type": null,
    "column_type_config": null
  }
]
render_cell

Rendered HTML for each cell using the render_cell plugin hook (See the render_cell() plugin hook documentation.)

The render_cell array has one item per row, in the same order as the rows array. Each object is keyed by column name. Only columns whose rendered value differs from the default are included.

{
  "rows": [
    {
      "id": 1,
      "content": "hello"
    },
    {
      "id": 4,
      "content": "RENDER_CELL_DEMO"
    }
  ],
  "render_cell": [
    {},
    {
      "content": "<strong>Custom rendered HTML</strong>"
    }
  ]
}
debug

Extra debug information dictionary. This is intended for development only and its shape is not part of the stable template contract. (The contents of this block are not a stable part of the Datasette API and may change without warning.)

GET /fixtures/facetable.json?_extra=debug

{
  "url_vars": {
    "database": "fixtures",
    "table": "facetable",
    "format": "json"
  },
  "resolved": "ResolvedTable(db=<Database: fixtures (mutable, size=274432)>, table='facetable', is_view=False)",
  "nofacet": null,
  "nosuggest": null
}
request

Dictionary with request details: url, path, full_path, host and args where args maps query string parameter names to their values.

GET /fixtures/facetable.json?_extra=request

{
  "url": "http://localhost/fixtures/facetable.json?_extra=request",
  "path": "/fixtures/facetable.json",
  "full_path": "/fixtures/facetable.json?_extra=request",
  "host": "localhost",
  "args": {
    "_extra": [
      "request"
    ]
  }
}
query

Details of the underlying SQL query as a dictionary with sql and params keys.

GET /fixtures/facetable.json?_size=1&_extra=query

{
  "sql": "select pk, created, planet_int, on_earth, state, _city_id, _neighborhood, tags, complex_array, distinct_some_null, n from facetable order by pk limit 2",
  "params": {}
}
column_types

Column type assignments for this table. A dictionary mapping column names to {"type": type_name, "config": config} dictionaries. (An empty object if no column types have been assigned. Column types can be assigned in configuration or using the set column type API.)

GET /fixtures/facetable.json?_size=0&_extra=column_types

This example is from an instance where the tags column has been assigned the json column type.

{
  "tags": {
    "type": "json",
    "config": null
  }
}
set_column_type_ui

Information needed to build an interface for assigning column types, or None if unavailable. When present it has path and columns keys; columns maps column names to current and options values. (null unless the current actor is allowed to use the set column type API for this table.)

Shape abbreviated to two columns, as seen by an actor with set-column-type permission. current is the column type currently assigned to each column and options lists the types that could be assigned to it.

{
  "path": "/fixtures/facetable/-/set-column-type",
  "columns": {
    "created": {
      "current": null,
      "options": [
        {
          "name": "email",
          "description": "Email address"
        },
        {
          "name": "json",
          "description": "JSON data"
        },
        {
          "name": "url",
          "description": "URL"
        }
      ]
    },
    "tags": {
      "current": {
        "type": "json",
        "config": null
      },
      "options": [
        {
          "name": "email",
          "description": "Email address"
        },
        {
          "name": "json",
          "description": "JSON data"
        },
        {
          "name": "url",
          "description": "URL"
        }
      ]
    }
  }
}
set_label_column_ui

Information needed to build an interface for setting the table's label column, or None if unavailable. (null unless the current actor is allowed to use the set label column API for this table.)

Shape abbreviated to five columns, as seen by an actor with set-label-column permission. saved is the label column or template saved with the API, configured is the label_column table configuration, detected is the label column Datasette detects. default is the label the table uses without a saved one, from its configuration if that can be used, otherwise the detected label column. current is the label in use.

{
  "path": "/fixtures/facetable/-/set-label-column",
  "saved": null,
  "configured": null,
  "detected": "state",
  "default": {
    "label_column": "state",
    "label_template": null,
    "source": "detected"
  },
  "current": {
    "label_column": "state",
    "label_template": null,
    "source": "detected"
  },
  "columns": [
    "pk",
    "created",
    "planet_int",
    "on_earth",
    "state"
  ]
}
metadata

Metadata dictionary for the table, database or stored query. Table and row metadata include a columns dictionary mapping column names to descriptions; stored query metadata returns the stored query configuration. (See Metadata for how to attach metadata to tables.)

GET /fixtures/facetable.json?_extra=metadata

This example is from an instance where the facetable table has a metadata description and a column description for its state column. The columns object is empty for tables with no column descriptions.

{
  "description": "A demo table of places, used to demonstrate facets",
  "columns": {
    "state": "Two letter US state code"
  }
}
extras

List of ?_extra= blocks that can be used on this page. Each item has name, description, toggle_url and selected keys.

Shape abbreviated from /fixtures/facetable.json?_extra=extras - the full response lists every extra described on this page. toggle_url is the current URL with that extra added or removed, and selected is true for extras included in the current request.

[
  {
    "name": "count",
    "description": "Total count of rows matching these filters",
    "toggle_url": "http://localhost/fixtures/facetable.json?_extra=extras&_extra=count",
    "selected": false
  },
  {
    "name": "extras",
    "description": "List of ?_extra= blocks that can be used on this page",
    "toggle_url": "http://localhost/fixtures/facetable.json",
    "selected": true
  }
]
database

Database name

GET /fixtures/facetable.json?_extra=database

"fixtures"
table

Table name

GET /fixtures/facetable.json?_extra=table

"facetable"
database_color

Color assigned to the database (A six character hex color, without the leading #, derived from a hash of the database name and used in the Datasette interface.)

GET /fixtures/facetable.json?_extra=database_color

"9403e5"
renderers

Dictionary mapping output format names such as json or plugin-provided renderer names to URLs for this data in that format.

GET /fixtures/facetable.json?_extra=renderers

Each key is the name of an output format, each value the URL for this data in that format. Plugins can add additional formats using the register_output_renderer() plugin hook.

{
  "json": "/fixtures/facetable.json?_extra=renderers&_labels=on",
  "tsv": "/fixtures/facetable.tsv?_extra=renderers&_labels=on",
  "csv": "/fixtures/facetable.csv?_extra=renderers&_labels=on"
}
custom_table_templates

List of custom template names considered for rendering table rows, in lookup order. (The first template in this list that exists will be used to render the table on the HTML version of this page. See Custom templates.)

GET /fixtures/facetable.json?_extra=custom_table_templates

[
  "_table-fixtures-facetable.html",
  "_table-table-fixtures-facetable.html",
  "_table.html"
]
sorted_facet_results

Facet result dictionaries sorted for display. Each item has the same shape as an entry from facet_results['results']. (The same data as facet_results, as a list in the order used by the HTML interface: facets from facet configuration first, then other facets ordered by their number of results.)

GET /fixtures/facetable.json?_facet=state&_extra=sorted_facet_results

[
  {
    "name": "state",
    "type": "column",
    "hideable": true,
    "toggle_url": "/fixtures/facetable.json?_extra=sorted_facet_results",
    "results": [
      {
        "value": "CA",
        "label": "CA",
        "count": 10,
        "toggle_url": "http://localhost/fixtures/facetable.json?_facet=state&_extra=sorted_facet_results&state=CA",
        "selected": false
      },
      {
        "value": "MI",
        "label": "MI",
        "count": 4,
        "toggle_url": "http://localhost/fixtures/facetable.json?_facet=state&_extra=sorted_facet_results&state=MI",
        "selected": false
      },
      {
        "value": "MC",
        "label": "MC",
        "count": 1,
        "toggle_url": "http://localhost/fixtures/facetable.json?_facet=state&_extra=sorted_facet_results&state=MC",
        "selected": false
      }
    ],
    "truncated": false
  }
]
table_definition

SQL definition for this table

GET /fixtures/facetable.json?_extra=table_definition

"CREATE TABLE facetable (\n    pk integer primary key,\n    created text,\n    planet_int integer,\n    on_earth integer,\n    state text,\n    _city_id integer,\n    _neighborhood text,\n    tags text,\n    complex_array text,\n    distinct_some_null,\n    n text,\n    FOREIGN KEY (\"_city_id\") REFERENCES [facet_cities](id)\n);"
view_definition

SQL definition for this view

GET /fixtures/simple_view.json?_extra=view_definition

"CREATE VIEW simple_view AS\n    SELECT content, upper(content) AS upper_content FROM simple_primary_key;"
is_view

Whether this resource is a view instead of a table

GET /fixtures/simple_view.json?_extra=is_view

true
private

Whether this resource is private to the current actor (true if the current actor can see this resource but an anonymous user could not. See Permissions.)

GET /fixtures/facetable.json?_extra=private

false
expandable_columns

List of foreign key columns that can be expanded with labels. Each item is a (foreign_key, label_column) pair where foreign_key is the SQLite foreign key dictionary and label_column is the label column in the referenced table, its label template if the label combines several columns, or None. (See Expanding foreign key references for how to expand these labels.)

GET /fixtures/facetable.json?_extra=expandable_columns

Each item is a [foreign_key, label_column] pair: the foreign key relationship, then the column in the other table that would be used as the label for each expanded value.

[
  [
    {
      "column": "_city_id",
      "other_table": "facet_cities",
      "other_column": "id"
    },
    "name"
  ]
]
expanded_columns

List of foreign key columns that have been expanded with labels on this page, using ?_labels=on or ?_label=column. Values in those columns are returned as {"value": ..., "label": ...} objects. (See Expanding foreign key references for how to expand these labels.)

GET /fixtures/facetable.json?_labels=on&_extra=expanded_columns

[
  "_city_id"
]
form_hidden_args

List of (name, value) pairs for hidden form fields used by the HTML table interface to preserve current query string options.

GET /fixtures/facetable.json?_facet=state&_size=1&_extra=form_hidden_args

[
  [
    "_facet",
    "state"
  ],
  [
    "_size",
    "1"
  ],
  [
    "_extra",
    "form_hidden_args"
  ]
]
m2m

Many-to-many relationships for the rows on this page, through junction tables. Maps each relationship name to a description of it, such as its junction table, related table, extra_columns and the actor's can_add and can_remove permissions, plus rows mapping each row path to its total and up to ?_m2m_size= related items. Each item has links, one for each junction table row, with its path, url and the values of its extra columns as through, text cut to 100 characters unless ?_m2m_truncate=0. See the many-to-many relationships section below. (May execute additional queries.)

GET /fixtures/roadside_attractions.json?_extra=m2m&_size=1

{
  "roadside_attraction_characteristics": {
    "name": "roadside_attraction_characteristics",
    "label": "attraction_characteristic",
    "junction": "roadside_attraction_characteristics",
    "junction_url": "/fixtures/roadside_attraction_characteristics",
    "table": "attraction_characteristic",
    "column": "characteristic_id",
    "other_column": "pk",
    "near_column": "attraction_id",
    "label_column": "name",
    "label_template": null,
    "can_add": false,
    "can_remove": false,
    "can_update": false,
    "can_create": false,
    "create_label_column": null,
    "extra_columns": [],
    "unique_pair": false,
    "junction_kind": "plain",
    "pill_columns": [],
    "pill_columns_more": 0,
    "pill_columns_error": null,
    "other_column_is_pk": true,
    "autocomplete_url": "/fixtures/attraction_characteristic/-/autocomplete",
    "timed_out": false,
    "error": null,
    "rows": {
      "1": {
        "total": 1,
        "total_capped": false,
        "truncated": false,
        "items": [
          {
            "value": 2,
            "label": "Paranormal",
            "url": "/fixtures/attraction_characteristic/2",
            "links": [
              {
                "path": "1",
                "url": "/fixtures/roadside_attraction_characteristics/1"
              }
            ]
          }
        ],
        "url": "/fixtures/attraction_characteristic?_m2m.roadside_attraction_characteristics=1",
        "junction_rows_url": "/fixtures/roadside_attraction_characteristics?attraction_id=1"
      }
    }
  }
}
m2m_through

When the table is filtered by exactly one ?_m2m.J=value filter, the junction table rows that link each row to that value, with the values of the junction table's extra columns, such as a role. relationship is the name of the relationship, J, and rows maps the path of each row on the page to its links, using the same row paths as the m2m extra. links is a list with one entry for each junction table row, with its path, url and extra column values as through. A junction table that can link the same pair of rows more than once lists up to 10 of them, with links_truncated set to true if there are more. This extra is null without exactly one ?_m2m.J=value filter, or if the junction table has no extra columns. If reading the links runs out of the relationship_time_limit_ms that the request's relationships share, or fails, or SQLite lacks its JSON functions, it is {} and the response has an m2m_through_error message. (May execute additional queries.)

Shape abbreviated from /m2m/people.json?_m2m.movie_actors=1&_extra=m2m_through.

{
  "relationship": "movie_actors",
  "rows": {
    "177": {
      "links": [
        {
          "path": "1,177",
          "url": "/m2m/movie_actors/1,177",
          "through": {
            "role": "Narrator"
          }
        }
      ],
      "links_truncated": false
    }
  }
}

Row JSON responses

The following extras are available for row JSON responses.

columns

List of column names returned by this table, row or query.

GET /fixtures/simple_primary_key/1.json?_extra=columns

[
  "id",
  "content"
]
primary_keys

List of primary key column names for this table, or an empty list if the table has no explicit primary key.

GET /fixtures/simple_primary_key/1.json?_extra=primary_keys

[
  "id"
]
column_details

SQLite schema details for columns in this table. The dictionary maps column names to objects describing the schema for each column. (Each object has type as the declared type string returned by SQLite, or "" if no type was declared; sqlite_type as the normalized SQLite affinity, one of TEXT, INTEGER, REAL, BLOB or NUMERIC; notnull as a boolean; default as the raw SQL default expression string, such as "42", "'hello'" or "datetime('now')", or null if there is no default; is_pk as a boolean; pk_position as the integer primary key position reported by SQLite, or 0 for columns that are not part of the primary key; and hidden as the integer value reported by SQLite's PRAGMA table_xinfo. hidden is 0 for normal columns, 1 for hidden virtual table columns, 2 for virtual generated columns and 3 for stored generated columns.)

GET /fixtures/binary_data/1.json?_extra=column_details

{
  "data": {
    "type": "BLOB",
    "sqlite_type": "BLOB",
    "notnull": false,
    "default": null,
    "is_pk": false,
    "pk_position": 0,
    "hidden": 0
  }
}
render_cell

Rendered HTML for each cell using the render_cell plugin hook (See the render_cell() plugin hook documentation.)

The render_cell object is keyed by column name. Only columns whose rendered value differs from the default are included. If a ?_shape= is specified render_cell is instead a list with one item, matching the rows list.

{
  "row": {
    "id": 4,
    "content": "RENDER_CELL_DEMO"
  },
  "render_cell": {
    "content": "<strong>Custom rendered HTML</strong>"
  }
}
debug

Extra debug information dictionary. This is intended for development only and its shape is not part of the stable template contract. (The contents of this block are not a stable part of the Datasette API and may change without warning.)

GET /fixtures/simple_primary_key/1.json?_extra=debug

{
  "url_vars": {
    "database": "fixtures",
    "table": "simple_primary_key",
    "pks": "1",
    "format": "json"
  },
  "resolved": {
    "table": "simple_primary_key",
    "sql": "select * from simple_primary_key where \"id\"=:p0",
    "params": {
      "p0": "1"
    },
    "pks": [
      "id"
    ],
    "pk_values": [
      "1"
    ]
  }
}
request

Dictionary with request details: url, path, full_path, host and args where args maps query string parameter names to their values.

GET /fixtures/simple_primary_key/1.json?_extra=request

{
  "url": "http://localhost/fixtures/simple_primary_key/1.json?_extra=request",
  "path": "/fixtures/simple_primary_key/1.json",
  "full_path": "/fixtures/simple_primary_key/1.json?_extra=request",
  "host": "localhost",
  "args": {
    "_extra": [
      "request"
    ]
  }
}
query

Details of the underlying SQL query as a dictionary with sql and params keys.

GET /fixtures/simple_primary_key/1.json?_extra=query

{
  "sql": "select * from simple_primary_key where \"id\"=:p0",
  "params": {
    "p0": "1"
  }
}
column_types

Column type assignments for this table. A dictionary mapping column names to {"type": type_name, "config": config} dictionaries. (An empty object if no column types have been assigned. Column types can be assigned in configuration or using the set column type API.)

GET /fixtures/facetable/1.json?_extra=column_types

This example is from an instance where the tags column has been assigned the json column type.

{
  "tags": {
    "type": "json",
    "config": null
  }
}
metadata

Metadata dictionary for the table, database or stored query. Table and row metadata include a columns dictionary mapping column names to descriptions; stored query metadata returns the stored query configuration. (See Metadata for how to attach metadata to tables.)

GET /fixtures/simple_primary_key/1.json?_extra=metadata

This table has no metadata, so only an empty columns object is returned.

{
  "columns": {}
}
extras

List of ?_extra= blocks that can be used on this page. Each item has name, description, toggle_url and selected keys.

Shape abbreviated from /fixtures/facetable.json?_extra=extras - the full response lists every extra described on this page. toggle_url is the current URL with that extra added or removed, and selected is true for extras included in the current request.

[
  {
    "name": "count",
    "description": "Total count of rows matching these filters",
    "toggle_url": "http://localhost/fixtures/facetable.json?_extra=extras&_extra=count",
    "selected": false
  },
  {
    "name": "extras",
    "description": "List of ?_extra= blocks that can be used on this page",
    "toggle_url": "http://localhost/fixtures/facetable.json",
    "selected": true
  }
]
database

Database name

GET /fixtures/simple_primary_key/1.json?_extra=database

"fixtures"
table

Table name

GET /fixtures/simple_primary_key/1.json?_extra=table

"simple_primary_key"
database_color

Color assigned to the database (A six character hex color, without the leading #, derived from a hash of the database name and used in the Datasette interface.)

GET /fixtures/simple_primary_key/1.json?_extra=database_color

"9403e5"
private

Whether this resource is private to the current actor (true if the current actor can see this resource but an anonymous user could not. See Permissions.)

GET /fixtures/simple_primary_key/1.json?_extra=private

false
foreign_key_tables

List of tables that link to this row using foreign keys. Each item includes the foreign key fields plus count for matching rows, count_capped and link for the filtered table URL. Each count stops at 10,000, with count_capped set to true if there are more. The counts are subject to the facet_time_limit_ms time limit: if that is exceeded every count is null. (May execute additional queries.)

GET /fixtures/simple_primary_key/1.json?_extra=foreign_key_tables

count is the number of rows in the other table that reference this row, and link is a URL to browse those rows.

[
  {
    "other_table": "complex_foreign_keys",
    "column": "id",
    "other_column": "f1",
    "count": 1,
    "count_capped": false,
    "link": "/fixtures/complex_foreign_keys?f1=1"
  },
  {
    "other_table": "complex_foreign_keys",
    "column": "id",
    "other_column": "f2",
    "count": 0,
    "count_capped": false,
    "link": "/fixtures/complex_foreign_keys?f2=1"
  },
  {
    "other_table": "complex_foreign_keys",
    "column": "id",
    "other_column": "f3",
    "count": 1,
    "count_capped": false,
    "link": "/fixtures/complex_foreign_keys?f3=1"
  },
  {
    "other_table": "foreign_key_references",
    "column": "id",
    "other_column": "foreign_key_with_blank_label",
    "count": 0,
    "count_capped": false,
    "link": "/fixtures/foreign_key_references?foreign_key_with_blank_label=1"
  },
  {
    "other_table": "foreign_key_references",
    "column": "id",
    "other_column": "foreign_key_with_label",
    "count": 1,
    "count_capped": false,
    "link": "/fixtures/foreign_key_references?foreign_key_with_label=1"
  }
]
foreign_key_details

Details of each foreign key that references this row, one item for each item in foreign_key_tables and in the same order, without the counts. Each item has the foreign key fields, the reference name to pass to the row delete API's clear_references, such as reviews.user_id, which is not tilde-encoded and is matched as a whole string, so pass it back exactly as given, the foreign key's on_delete action from the schema (NO ACTION unless one is declared), can_clear and cannot_clear_reason: not nullable, part of primary key, permission (no update-row on that table) or immutable, or null if it can be cleared. junction is true if the other table is the junction table of a many-to-many relationship of this table, through that foreign key, whose links the row delete API's delete_m2m can delete: a junction table whose links can be edited, or a relationship listed in the m2m configuration. This does not depend on whether the m2m configuration shows the relationship, or on SQLite's JSON functions. Those items also have the relationship name for delete_m2m as m2m, the related table as m2m_table, the junction table's foreign key to it as m2m_column, junction_kind and can_remove, whether the actor can delete the junction table's rows. For other items junction is false and those keys are null. junction_unknown is true for every item if working out which tables are junction tables failed, in which case the error is logged and every junction is false, even for a junction table, and false otherwise. Used by the row delete dialog, with foreign_key_tables, to say what refers to the row.

GET /fixtures/simple_primary_key/1.json?_extra=foreign_key_details

[
  {
    "other_table": "complex_foreign_keys",
    "column": "id",
    "other_column": "f1",
    "reference": "complex_foreign_keys.f1",
    "on_delete": "NO ACTION",
    "can_clear": false,
    "cannot_clear_reason": "permission",
    "junction": false,
    "m2m": null,
    "m2m_table": null,
    "m2m_column": null,
    "junction_kind": null,
    "can_remove": null,
    "junction_unknown": false
  },
  {
    "other_table": "complex_foreign_keys",
    "column": "id",
    "other_column": "f2",
    "reference": "complex_foreign_keys.f2",
    "on_delete": "NO ACTION",
    "can_clear": false,
    "cannot_clear_reason": "permission",
    "junction": false,
    "m2m": null,
    "m2m_table": null,
    "m2m_column": null,
    "junction_kind": null,
    "can_remove": null,
    "junction_unknown": false
  },
  {
    "other_table": "complex_foreign_keys",
    "column": "id",
    "other_column": "f3",
    "reference": "complex_foreign_keys.f3",
    "on_delete": "NO ACTION",
    "can_clear": false,
    "cannot_clear_reason": "permission",
    "junction": false,
    "m2m": null,
    "m2m_table": null,
    "m2m_column": null,
    "junction_kind": null,
    "can_remove": null,
    "junction_unknown": false
  },
  {
    "other_table": "foreign_key_references",
    "column": "id",
    "other_column": "foreign_key_with_blank_label",
    "reference": "foreign_key_references.foreign_key_with_blank_label",
    "on_delete": "NO ACTION",
    "can_clear": false,
    "cannot_clear_reason": "permission",
    "junction": false,
    "m2m": null,
    "m2m_table": null,
    "m2m_column": null,
    "junction_kind": null,
    "can_remove": null,
    "junction_unknown": false
  },
  {
    "other_table": "foreign_key_references",
    "column": "id",
    "other_column": "foreign_key_with_label",
    "reference": "foreign_key_references.foreign_key_with_label",
    "on_delete": "NO ACTION",
    "can_clear": false,
    "cannot_clear_reason": "permission",
    "junction": false,
    "m2m": null,
    "m2m_table": null,
    "m2m_column": null,
    "junction_kind": null,
    "can_remove": null,
    "junction_unknown": false
  }
]
m2m

Many-to-many relationships for the rows on this page, through junction tables. Maps each relationship name to a description of it, such as its junction table, related table, extra_columns and the actor's can_add and can_remove permissions, plus rows mapping each row path to its total and up to ?_m2m_size= related items. Each item has links, one for each junction table row, with its path, url and the values of its extra columns as through, text cut to 100 characters unless ?_m2m_truncate=0. See the many-to-many relationships section below. (May execute additional queries.)

GET /fixtures/roadside_attractions/4.json?_extra=m2m

{
  "roadside_attraction_characteristics": {
    "name": "roadside_attraction_characteristics",
    "label": "attraction_characteristic",
    "junction": "roadside_attraction_characteristics",
    "junction_url": "/fixtures/roadside_attraction_characteristics",
    "table": "attraction_characteristic",
    "column": "characteristic_id",
    "other_column": "pk",
    "near_column": "attraction_id",
    "label_column": "name",
    "label_template": null,
    "can_add": false,
    "can_remove": false,
    "can_update": false,
    "can_create": false,
    "create_label_column": null,
    "extra_columns": [],
    "unique_pair": false,
    "junction_kind": "plain",
    "pill_columns": [],
    "pill_columns_more": 0,
    "pill_columns_error": null,
    "other_column_is_pk": true,
    "autocomplete_url": "/fixtures/attraction_characteristic/-/autocomplete",
    "timed_out": false,
    "error": null,
    "rows": {
      "4": {
        "total": 2,
        "total_capped": false,
        "truncated": false,
        "items": [
          {
            "value": 2,
            "label": "Paranormal",
            "url": "/fixtures/attraction_characteristic/2",
            "links": [
              {
                "path": "3",
                "url": "/fixtures/roadside_attraction_characteristics/3"
              }
            ]
          },
          {
            "value": 1,
            "label": "Museum",
            "url": "/fixtures/attraction_characteristic/1",
            "links": [
              {
                "path": "5",
                "url": "/fixtures/roadside_attraction_characteristics/5"
              }
            ]
          }
        ],
        "url": "/fixtures/attraction_characteristic?_m2m.roadside_attraction_characteristics=4",
        "junction_rows_url": "/fixtures/roadside_attraction_characteristics?attraction_id=4"
      }
    }
  }
}

Query JSON responses

The following extras are available for arbitrary SQL query responses and stored, named query responses.

columns

List of column names returned by this table, row or query.

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=columns

[
  "one"
]
render_cell

Rendered HTML for each cell using the render_cell plugin hook (See the render_cell() plugin hook documentation.)

The render_cell array has one item per query result row, in the same order as the rows array. Each object is keyed by column name. Only columns whose rendered value differs from the default are included.

{
  "rows": [
    {
      "content": "RENDER_CELL_DEMO"
    }
  ],
  "render_cell": [
    {
      "content": "<strong>Custom rendered HTML</strong>"
    }
  ]
}
debug

Extra debug information dictionary. This is intended for development only and its shape is not part of the stable template contract. (The contents of this block are not a stable part of the Datasette API and may change without warning.)

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=debug

{
  "url_vars": {
    "database": "fixtures",
    "format": "json"
  }
}
request

Dictionary with request details: url, path, full_path, host and args where args maps query string parameter names to their values.

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=request

{
  "url": "http://localhost/fixtures/-/query.json?sql=select+1+as+one&_extra=request",
  "path": "/fixtures/-/query.json",
  "full_path": "/fixtures/-/query.json?sql=select+1+as+one&_extra=request",
  "host": "localhost",
  "args": {
    "sql": [
      "select 1 as one"
    ],
    "_extra": [
      "request"
    ]
  }
}
query

Details of the underlying SQL query as a dictionary with sql and params keys.

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=query

{
  "sql": "select 1 as one",
  "params": {}
}

GET /fixtures/neighborhood_search.json?text=town&_extra=query

{
  "sql": "\nselect _neighborhood, facet_cities.name, state\nfrom facetable\n    join facet_cities\n        on facetable._city_id = facet_cities.id\nwhere _neighborhood like '%' || :text || '%'\norder by _neighborhood;\n",
  "params": {
    "text": "town"
  }
}
metadata

Metadata dictionary for the table, database or stored query. Table and row metadata include a columns dictionary mapping column names to descriptions; stored query metadata returns the stored query configuration. (See Metadata for how to attach metadata to tables.)

GET /fixtures/neighborhood_search.json?text=town&_extra=metadata

For stored queries this returns the full configuration of the query, including the stored query options. For ?sql= queries it returns an empty object.

{
  "database": "fixtures",
  "name": "neighborhood_search",
  "sql": "\nselect _neighborhood, facet_cities.name, state\nfrom facetable\n    join facet_cities\n        on facetable._city_id = facet_cities.id\nwhere _neighborhood like '%' || :text || '%'\norder by _neighborhood;\n",
  "title": "Search neighborhoods",
  "description": null,
  "description_html": null,
  "hide_sql": false,
  "fragment": null,
  "parameters": [],
  "is_write": false,
  "is_private": false,
  "is_trusted": true,
  "owner_id": null,
  "on_success_message": null,
  "on_success_message_sql": null,
  "on_success_redirect": null,
  "on_error_message": null,
  "on_error_redirect": null
}
extras

List of ?_extra= blocks that can be used on this page. Each item has name, description, toggle_url and selected keys.

Shape abbreviated from /fixtures/facetable.json?_extra=extras - the full response lists every extra described on this page. toggle_url is the current URL with that extra added or removed, and selected is true for extras included in the current request.

[
  {
    "name": "count",
    "description": "Total count of rows matching these filters",
    "toggle_url": "http://localhost/fixtures/facetable.json?_extra=extras&_extra=count",
    "selected": false
  },
  {
    "name": "extras",
    "description": "List of ?_extra= blocks that can be used on this page",
    "toggle_url": "http://localhost/fixtures/facetable.json",
    "selected": true
  }
]
database

Database name

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=database

"fixtures"
database_color

Color assigned to the database (A six character hex color, without the leading #, derived from a hash of the database name and used in the Datasette interface.)

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=database_color

"9403e5"
private

Whether this resource is private to the current actor (true if the current actor can see this resource but an anonymous user could not. See Permissions.)

GET /fixtures/-/query.json?sql=select+1+as+one&_extra=private

false

Many-to-many relationships

The many-to-many relationships that Datasette shows on table and row pages are available in table and row JSON using two extras. Both run extra queries, so table and row JSON only include many-to-many data when one of them is requested. Neither changes the rows of the response.

  • ?_extra=m2m adds an "m2m" key describing each relationship, with the related rows of every row on the page. See The m2m extra.

  • ?_extra=m2m_through adds an "m2m_through" key with the extra columns of the matching links of each row of a table filtered by a relationship. See The m2m_through extra.

These special table arguments change what the m2m extra returns:

  • ?_m2m_size=N sets how many related rows are returned for each row, up to 100. The default is 5 for table JSON and 20 for row JSON. It counts related rows, not the links between them.

  • ?_m2m_truncate=0 returns the text values of extra columns in full, rather than cut to 100 characters, see Values that are cut short.

  • ?_col= and ?_nocol= choose which relationships the m2m extra returns for table JSON, the same as the many-to-many columns of the table page: with any ?_col=, only those it lists, such as ?_col=title&_col=m2m:movie_actors, and never those in ?_nocol=. See Special table arguments.

These extras are ignored by CSV and TSV exports, which only include the table's own columns.

The m2m extra

?_extra=m2m adds an "m2m" key describing each relationship, with the related rows for every row on the page. Here is a single relationship from /m2m/movies/2.json?_extra=m2m&_m2m_size=3:

{
  "m2m": {
    "movie_tags": {
      "name": "movie_tags",
      "label": "tags",
      "junction": "movie_tags",
      "junction_url": "/m2m/movie_tags",
      "table": "tags",
      "column": "tag_id",
      "other_column": "id",
      "near_column": "movie_id",
      "label_column": "tag",
      "label_template": null,
      "can_add": true,
      "can_remove": true,
      "can_update": true,
      "can_create": true,
      "create_label_column": "tag",
      "extra_columns": [],
      "unique_pair": false,
      "junction_kind": "plain",
      "pill_columns": [],
      "pill_columns_more": 0,
      "pill_columns_error": null,
      "other_column_is_pk": true,
      "autocomplete_url": "/m2m/tags/-/autocomplete",
      "timed_out": false,
      "error": null,
      "rows": {
        "2": {
          "total": 7,
          "total_capped": false,
          "truncated": true,
          "items": [
            {
              "value": 18,
              "label": "dystopia",
              "url": "/m2m/tags/18",
              "links": [
                {
                  "path": "21",
                  "url": "/m2m/movie_tags/21"
                }
              ]
            },
            {
              "value": 17,
              "label": "space",
              "url": "/m2m/tags/17",
              "links": [
                {
                  "path": "20",
                  "url": "/m2m/movie_tags/20"
                }
              ]
            },
            {
              "value": 12,
              "label": "twist-ending",
              "url": "/m2m/tags/12",
              "links": [
                {
                  "path": "19",
                  "url": "/m2m/movie_tags/19"
                }
              ]
            }
          ],
          "url": "/m2m/tags?_m2m.movie_tags=2",
          "junction_rows_url": "/m2m/movie_tags?movie_id=2"
        }
      }
    }
  }
}

Each relationship is keyed by its name and has the following keys:

name

The relationship name, used by the ?_m2m.NAME= filters and the write APIs.

label

The text shown for this relationship in the HTML interface: the name of the related table, the configured label, or for a self-referential relationship the table name followed by the column, such as movies (related_id).

junction and junction_url

The junction table, and the path of its table page, such as /m2m/movie_tags. The table page links to it from the "via movie_tags" part of the relationship's column heading. Relationships are only included for actors who can view the junction table, so they can always follow it.

table

The related table.

column

The column in the junction table that points at the related table.

near_column

The column in the junction table that points at this table.

other_column

The column in the related table that column refers to.

other_column_is_pk

true if other_column is the primary key of the related table.

label_column and label_template

The label column of the related table, or null if it does not have one. If its label is a template that combines several columns, label_column is null and label_template is the template, such as "{app_label}: {model}", otherwise label_template is null.

autocomplete_url

The autocomplete endpoint for searching the related table for rows to link, or null if other_column is not its primary key.

can_add, can_remove and can_update

Whether the current actor can add links, remove them, or change their extra columns, which requires the insert-row, delete-row or update-row permission on the junction table. All three are false in an immutable database, and for a relationship through a repeatable junction table (junction_kind is repeatable) unless the relationship is listed in the m2m table configuration.

can_create and create_label_column

can_create is true if the current actor can create a new row of the related table from just a label, and link it, using a create item in the link API. create_label_column is the column that the label is for, the related table's label column, if rows can be created from a label, otherwise null. Creating needs can_add, the insert-row permission on the related table, and a related table that a row can be made for from its label alone: it has a label column, not a label template, its primary key is the single column other_column, which is either an INTEGER primary key that SQLite assigns or the label column itself (such as a slug text primary key), and every other column can be null, has a default or is generated. Extra columns of the junction table that are required do not stop it, since they are set for the new link.

extra_columns

The junction table's extra columns, such as a role, or an empty list if it has none. Each one is an object with the column's name, its declared type (an empty string if it has none), notnull (true if the column is NOT NULL), has_default (true if it has a default value), default (the default as a SQL expression, or null), sqlite_type (the type affinity, such as TEXT), column_type (an assigned column type as {"type", "config"}, or null) and autocomplete_url (an autocomplete endpoint if the column is a foreign key to a table with a single-column primary key, otherwise null). A column that is notnull without a default must be given a value when a link is added.

junction_kind

The kind of junction table: plain for a plain junction table, extra_columns for a junction table with extra columns, or repeatable for a repeatable junction table. Unless they are configured, the links of relationships through repeatable junction tables cannot be added, removed or changed through the relationship, by the link write API or the m2m key of the row APIs; the junction table's rows can still be changed with the ordinary row APIs.

unique_pair

true if the junction table can link a pair of rows only once: its primary key, or a unique index without a where clause, is exactly the two foreign key columns, in either order. If it is false the same pair can be linked more than once, and removing the related row with the link API removes every link between them.

pill_columns, pill_columns_more and pill_columns_error

pill_columns lists the extra columns whose values are shown in each related row's pill on the table and row pages, as described in Pills, or is an empty list if none are shown. pill_columns_more is the number of the junction table's other extra columns, which the pills show as "+N" after the values: 2 for movie_crew (movie_id, person_id, job, department, credited) configured to show just job. It is 0 when pill_columns is configured as false or [], or could not be used. A link gets a right half in its pill if it has a non-empty value in one of the pill_columns, or if pill_columns_more is not 0. The tooltip of that right half lists every value in the link's through. pill_columns_error is a message saying why the pill_columns configuration of the relationship could not be used, such as an unknown column name, in which case pill_columns is empty, otherwise null.

timed_out and error

timed_out is true if the query for this relationship ran out of the time left of relationship_time_limit_ms, which the relationships of a request share, and error is an error message if the query failed. In both cases rows is an empty object.

rows

The related rows for each row on the page, keyed by that row's path - the same key that is used for ?_shape=object. Add row_paths to ?_extra= to get the path of each row in rows, in order. Every row on the page is included, even if it has no related rows, apart from rows whose linking column (usually the primary key, possibly another unique column) is null, which cannot have any. The linking column is read for every row even if it is left out of the page with ?_col= or ?_nocol=.

Each value in rows has these keys:

total

The number of related rows, counted up to 10,000.

total_capped

true if there are more than 10,000 related rows, in which case total is 10000.

truncated

true if items does not include every related row.

items

Up to ?_m2m_size= related rows, in descending order of value. Each has the value stored in the junction table, a label, the url of the related row and its links, described below. If the related table has no label column the label is the value as a string.

url

The URL of the related table filtered to just the rows related to this row, using a ?_m2m. filter.

junction_rows_url

The URL of the junction table filtered to the links of this row: the rows whose near_column holds this row's value, such as /m2m/movie_tags?movie_id=2. The value is the one in this row's linking column, which is the primary key unless the junction table's foreign key points at another column. The "via movie_tags" part of the row page's heading for the relationship links to it.

If the relationships themselves cannot be worked out, for example because reading the database schema failed, the m2m extra is an empty object and the response has a top-level m2m_error key with the message, such as "Could not detect many-to-many relationships: ...". The error is logged, and the table and row pages are shown without relationship columns or "Related tables" filters. The write APIs fail with an error in this case. Responses without that problem have no m2m_error key.

The same happens, without logging anything, on a build of SQLite that does not have its JSON functions: the m2m extra is {} and m2m_error is "Many-to-many relationships are not shown: displaying them needs SQLite's JSON functions, which this build of SQLite does not have". Unlike a failure to work out the relationships, the write APIs still work on such a build.

If the table has more than 10 relationships and no m2m configuration list, the m2m extra has at most the first 10 detected. See at most 10 relationships for each table.

Values that are cut short

Text values in through longer than 100 characters are cut to their first 100 characters, counted in characters rather than bytes, and the link lists the names of the columns that were cut as truncated_columns. Binary values are shown as a <Binary: N bytes> string. Numbers and labels are never cut:

{
  "path": "85",
  "url": "/m2m/reviews/85",
  "through": {
    "stars": 4,
    "body": "A slow first hour, then the best heist sequence I have seen in years. The score alone is worth the"
  },
  "truncated_columns": [
    "body"
  ]
}

Add ?_m2m_truncate=0 to get every value in full, with no truncated_columns keys, as the row edit dialog does. 0 is the only value it takes: anything else is a 400 error. This applies to the m2m extra, for tables and rows, and to the pills on the HTML table and row pages. The m2m_through extra, and the responses of the write APIs, always return values in full.

The m2m_through extra

When a table is filtered using exactly one ?_m2m.NAME=value filter, ?_extra=m2m_through adds an "m2m_through" key with the extra columns of the links between each row and that value. /m2m/people.json?_m2m.movie_actors=1&_extra=m2m_through&_size=2 returns the first two actors in movie 1, with their roles in that movie (abbreviated):

{
  "m2m_through": {
    "relationship": "movie_actors",
    "rows": {
      "37": {
        "links": [
          {
            "path": "1,37",
            "url": "/m2m/movie_actors/1,37",
            "through": {
              "role": null
            }
          }
        ],
        "links_truncated": false
      },
      "177": {
        "links": [
          {
            "path": "1,177",
            "url": "/m2m/movie_actors/1,177",
            "through": {
              "role": "Narrator"
            }
          }
        ],
        "links_truncated": false
      }
    }
  },
  "rows": [
    {
      "id": 37,
      "name": "Barbara Clarke 37"
    },
    {
      "id": 177,
      "name": "Barbara Hamilton 177"
    }
  ]
}

relationship is the name of the relationship used by the filter. rows maps the path of each row on the page to its links, using the same row paths as the rows of the m2m extra and the row_paths extra. Rows whose linking column is null are left out.

links is always a list, with one entry for each junction table row that links the row to the filter's value, in the format of the links of the m2m extra. A junction table that can link the same pair of rows more than once gives up to 10 links, and links_truncated is true if there were more. /m2m/users.json?_m2m.reviews=40&_extra=m2m_through returns the users who reviewed movie 40, one of whom reviewed it twice (abbreviated):

{
  "m2m_through": {
    "relationship": "reviews",
    "rows": {
      "1": {
        "links": [
          {
            "path": "83",
            "url": "/m2m/reviews/83",
            "through": {
              "stars": 2,
              "body": "First impression: not for me."
            }
          },
          {
            "path": "84",
            "url": "/m2m/reviews/84",
            "through": {
              "stars": 5,
              "body": "Second viewing: I was wrong."
            }
          }
        ],
        "links_truncated": false
      }
    }
  }
}

m2m_through is null without exactly one ?_m2m.NAME=value filter, or if the junction table has no extra columns. If reading the links takes too long or fails, it is {} and the response has an m2m_through_error message.

Counting all matching rows

POST /<database>/<table>/-/count returns an exact count of the rows matching the table's query string filters:

POST /fixtures/facetable/-/count?state=CA

{"ok": true, "count": 10}

The endpoint supports the same column, search and plugin filters as the table page. Pagination and display options such as _next, _size and _sort do not affect the count.

This requires view-table permission. execute-sql permission is only needed if using _where filters.

Unlike the count extra, this count is not capped by the row count limit. The usual SQL time limit still applies; a timed-out count returns a 400 JSON error.

Table autocomplete

The /<database>/<table>/-/autocomplete endpoint returns up to 10 primary key matches for a table, intended for building autocomplete interfaces such as foreign key pickers.

GET /<database>/<table>/-/autocomplete?q=search

The q parameter is required. If it is omitted or blank, the endpoint returns an empty "rows" list.

The response includes a "pks" object containing the primary key value or values for each row, and a "path" which is the last part of the URL to that row's page, /<database>/<table>/<path>. "path" is null for a row with a null primary key, which has no page. If Datasette can detect a label column, or one has been configured using label_column, each row will also include "label". A binary value is returned as a {"$base64": true, "encoded": "..."} object, as it is in table JSON.

{
    "rows": [
        {
            "pks": {
                "id": 1
            },
            "path": "1",
            "label": "Example row"
        }
    ]
}

The endpoint searches the primary key column or columns and the label column using escaped SQL LIKE queries. A single-column primary key exact match is returned first. Other matches are ordered by the shortest matching label value where a label column is available.

The initial search runs with a 500ms time limit. If that query times out, Datasette falls back to a prefix match against the first primary key column so SQLite can use the primary key index.

Table arguments

The Datasette table view takes a number of special query string arguments.

Column filter arguments

You can filter the data returned by the table based on column values using a query string argument.

?column__exact=value or ?_column=value

Returns rows where the specified column exactly matches the value.

A value that looks like a number matches numbers as well as text if the column has no declared type, which is the case for a column in a view that is calculated by an expression such as count(*) or sum(amount). ?total=5 returns rows where total is the number 5 or the text "5". The same applies to __not, __in and __notin.

?column__not=value

Returns rows where the column does not match the value.

?column__contains=value

Rows where the string column contains the specified value (column like "%value%" in SQL).

?column__notcontains=value

Rows where the string column does not contain the specified value (column not like "%value%" in SQL).

?column__endswith=value

Rows where the string column ends with the specified value (column like "%value" in SQL).

?column__startswith=value

Rows where the string column starts with the specified value (column like "value%" in SQL).

?column__gt=value

Rows which are greater than the specified value.

?column__gte=value

Rows which are greater than or equal to the specified value.

?column__lt=value

Rows which are less than the specified value.

?column__lte=value

Rows which are less than or equal to the specified value.

?column__like=value

Match rows with a LIKE clause, case insensitive and with % as the wildcard character.

?column__notlike=value

Match rows that do not match the provided LIKE clause.

?column__glob=value

Similar to LIKE but uses Unix wildcard syntax and is case sensitive.

?column__in=value1,value2,value3

Rows where column matches any of the provided values.

You can use a comma separated string, or you can use a JSON array.

The JSON array option is useful if one of your matching values itself contains a comma:

?column__in=["value","value,with,commas"]

?column__notin=value1,value2,value3

Rows where column does not match any of the provided values. The inverse of __in=. Also supports JSON arrays.

?column__arraycontains=value

Works against columns that contain JSON arrays - matches if any of the values in that array match the provided value.

This is only available if the json1 SQLite extension is enabled.

?column__arraynotcontains=value

Works against columns that contain JSON arrays - matches if none of the values in that array match the provided value.

This is only available if the json1 SQLite extension is enabled.

?column__date=value

Column is a datestamp occurring on the specified YYYY-MM-DD date, e.g. 2018-01-02.

?column__isnull=1

Matches rows where the column is null.

?column__notnull=1

Matches rows where the column is not null.

?column__isblank=1

Matches rows where the column is blank, meaning null or the empty string.

?column__notblank=1

Matches rows where the column is not blank.

Special table arguments

?_col=COLUMN1&_col=COLUMN2

List specific columns to display. These will be shown along with any primary keys. A single empty ?_col= shows the primary keys alone.

This is the complete list of columns for the table page, including its relationship columns, in the order to show them. A relationship column is m2m: and the name of a many-to-many relationship, such as m2m:movie_actors, or ref: and a table and column with a foreign key that points at this table, such as ref:reviews.movie_id. For example ?_col=title&_col=m2m:movie_actors&_col=year. With ?_col=, relationship columns it does not list are not shown. Without it, the default relationship columns follow the table's own columns. Any relationship that can be shown can be listed, including many-to-many relationships beyond the first ten, and an unknown one is a 400 error. A column of the table whose name looks like a relationship column, such as m2m:x, is still a column of the table.

The "Choose columns" dialog, opened by the Columns button above the table, sets this, as does dragging a heading to move or hide its column. Each heading of the HTML table has its value as a data-col-value attribute.

Relationship columns only affect the HTML table and the m2m extra: they do not change the columns returned for each row.

?_nocol=COLUMN1&_nocol=COLUMN2

List specific columns to hide - any column not listed will be displayed. Primary keys cannot be hidden. This hides relationship columns too, such as ?_nocol=m2m:movie_actors.

?_labels=on/off

Expand foreign key references for every possible column. See below.

?_label=COLUMN1&_label=COLUMN2

Expand foreign key references for one or more specified columns.

?_size=1000 or ?_size=max

Sets a custom page size. This cannot exceed the max_returned_rows limit passed to datasette serve. Use max to get max_returned_rows.

?_sort=COLUMN

Sorts the results by the specified column.

?_sort_desc=COLUMN

Sorts the results by the specified column in descending order.

?_search=keywords

For SQLite tables that have been configured for full-text search executes a search with the provided keywords.

?_search_COLUMN=keywords

Like _search= but allows you to specify the column to be searched, as opposed to searching all columns that have been indexed by FTS.

?_searchmode=raw

With this option, queries passed to ?_search= or ?_search_COLUMN= will not have special characters escaped. This means you can make use of the full set of advanced SQLite FTS syntax, though this could potentially result in errors if the wrong syntax is used.

?_where=SQL-fragment

If the execute-sql permission is enabled, this parameter can be used to pass one or more additional SQL fragments to be used in the WHERE clause of the SQL used to query the table.

This is particularly useful if you are building a JavaScript application that needs to do something creative but still wants the other conveniences provided by the table view (such as faceting) and hence would like not to have to construct a completely custom SQL query.

Some examples:

?_m2m.TABLE=value

Filter rows by a many-to-many relationship through another table, known as a junction table. TABLE must have a foreign key to the current table and a foreign key to a third table, and value is a value of that second foreign key, usually the primary key of a row in the third table.

For example, roadside_attraction_characteristics has an attraction_id foreign key to roadside_attractions and a characteristic_id foreign key to attraction_characteristic. To show just the attractions that have the characteristic with ID 1 ("Museum"):

?_m2m.roadside_attraction_characteristics=1

Here's an example.

Add a lookup to the key to change how the value is matched:

  • ?_m2m.TABLE=value or ?_m2m.TABLE__exact=value: rows related to value.

  • ?_m2m.TABLE__not=value: rows not related to value, including rows with no related rows at all.

  • ?_m2m.TABLE__in=value1,value2: rows related to any of the values. A JSON list such as ["value1","value2"] can be used for values that contain commas.

  • ?_m2m.TABLE__notin=value1,value2: rows related to none of the values.

Repeating a key requires all of the values: ?_m2m.TABLE=1&_m2m.TABLE=2 returns rows that are related to both 1 and 2.

If the junction table has more than one foreign key to other tables, or both of its foreign keys point at the current table (for example a follows table with follower_id and followed_id columns), name the foreign key column to match against: ?_m2m.TABLE.COLUMN=value. The other foreign key to the current table is then used to find the matching rows.

Table and column names that contain a full stop must be tilde encoded, so . is written as ~2E.

A table or column name that itself ends in __not, __in, __notin or __exact, such as a junction table called tags__in, would be read as that lookup, so add __exact to filter by it: ?_m2m.tags__in__exact=1, or ?_m2m.tags__in__not=1 for the other lookups. The URLs that Datasette builds for these filters, such as the "N total" links, facet links and the filter form, do this for you.

The actor must have permission to view the junction table. A junction table the actor cannot view returns the same 400 error as one that does not exist.

Use Facet by many-to-many relationship to show counts for each related value, with links that apply these filters. The filter form on the HTML table page shows these filters as rows alongside the column filters, and can add them, see Filter and facet parameters.

The names used by these filters are the same relationship names that Datasette uses when it shows many-to-many relationships on table and row pages, and the "N total" links on those pages use these filters.

This replaces the ?_through={json} parameter from earlier releases. For now a table URL with ?_through={"table": "TABLE", "column": "COLUMN", "value": "value"} redirects to the same URL with ?_m2m.TABLE.COLUMN=value in its place, see the upgrade guide. This redirect will be removed in a later release.

?_next=TOKEN

Pagination by continuation token - pass the token that was returned in the "next" property by the previous page.

?_facet=column

Facet by column. Can be applied multiple times, see Facets. Only works on the default JSON output, not on any of the custom shapes.

?_facet_size=100

Increase the number of facet results returned for each facet. Use ?_facet_size=max for the maximum available size, determined by max_returned_rows.

?_nofacet=1

Disable all facets and facet suggestions for this page, including any defined by Facets in configuration.

?_nosuggest=1

Disable facet suggestions for this page.

?_nocount=1

Disable the select count(*) query used on this page - a count of None will be returned instead.

?_m2m_size=N

The number of related rows to show for each many-to-many relationship, up to 100. Defaults to 5 on the table page and 20 on the row page. Also applies to the m2m extra and the responses of the link API. A larger value is treated as 100, and a value that is not an integer, or is negative, returns a 400 error. ?_m2m_size=0 returns just the counts.

?_m2m_truncate=0

Return the text values of the extra columns of many-to-many links in full, rather than cut to 100 characters, in the pills on the HTML table and row pages and in the m2m extra. See Values that are cut short.

Expanding foreign key references

Datasette can detect foreign key relationships and resolve those references into labels. The HTML interface does this by default for every detected foreign key column - you can turn that off using ?_labels=off.

You can request foreign keys be expanded in JSON using the _labels=on or _label=COLUMN special query string parameters. Here's what an expanded row looks like:

[
    {
        "rowid": 1,
        "TreeID": 141565,
        "qLegalStatus": {
            "value": 1,
            "label": "Permitted Site"
        },
        "qSpecies": {
            "value": 1,
            "label": "Myoporum laetum :: Myoporum"
        },
        "qAddress": "501X Baker St",
        "SiteOrder": 1
    }
]

The column in the foreign key table that is used for the label can be specified in datasette.yaml - see label_column.

A value is only expanded if a label was found for it. A foreign key that refers to a table with no label column is returned as the plain value, as is a value that does not match a row in the other table.

Discovering the JSON for a page

Most of the HTML pages served by Datasette provide a mechanism for discovering their JSON equivalents using the HTML link mechanism.

You can find this near the top of the source code of those pages, looking like this:

<link rel="alternate"
  type="application/json+datasette"
  href="https://latest.datasette.io/fixtures/sortable.json">

The JSON URL is also made available in a Link HTTP header for the page:

Link: <https://latest.datasette.io/fixtures/sortable.json>; rel="alternate"; type="application/json+datasette"

Enabling CORS

If you start Datasette with the --cors option, each JSON endpoint will be served with the following additional HTTP headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Expose-Headers: Link, Datasette-Truncated, Datasette-Max-Returned-Rows
Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS
Access-Control-Max-Age: 3600

This allows JavaScript running on any domain to make cross-origin requests to interact with the Datasette API.

If you start Datasette without the --cors option only JavaScript running on the same domain as Datasette will be able to access the API.

Here's how to serve data.db with CORS enabled:

datasette data.db --cors

The JSON write API

Datasette provides a write API for JSON data. This is a POST-only API that requires an authenticated API token, see API Tokens. The token will need to have the specified Permissions.

The request body is always parsed as JSON, regardless of the request's Content-Type header - a body that is not valid JSON returns a 400 error. Cross-site request forgery is prevented by Datasette's Origin and Sec-Fetch-Site header checks rather than by content type requirements.

The row-based write APIs can write binary values in JSON using Datasette's Base64 representation for BLOB data.

Structured inserts, upserts, updates and deletes only support ordinary SQLite tables. Virtual tables and their internal shadow tables are rejected, including when adding rows to an existing table through the create-table API. Writes to ordinary content tables can still update full-text search indexes through configured triggers.

Executing write SQL

Actors with the execute-write-sql permission can execute arbitrary writable SQL against a mutable database using /-/execute-write.

POST /<database>/-/execute-write
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>

The request body must include a "sql" string. Named SQL parameters can be provided using the optional "params" object:

{
    "sql": "insert into dogs (name) values (:name)",
    "params": {
        "name": "Cleo"
    }
}

The SQL must be writable. Read-only select queries should use the regular custom SQL query JSON API instead.

Datasette analyzes the SQL before executing it. The actor must have execute-write-sql permission for the database, and must also have any permissions required by the operations in the SQL. For example, inserts and updates against a table require insert-row, update-row and delete-row permissions for that table. Reads performed as part of the write, such as insert into dogs select ... from other_table, require view-table permission on the source table. Schema changes require create-table, alter-table or drop-table permissions as appropriate.

Unsupported SQL operations are rejected by default. VACUUM is not allowed in arbitrary write SQL, and writes to SQLite virtual tables or shadow tables are rejected. SQL functions are allowed and are not separately restricted by Datasette permissions.

A successful response includes a message, the SQLite rowcount, a "rows" list, a "truncated" flag and a summary of the operations that were executed:

The shape of the "analysis" block is not part of the stable API and may change in future Datasette releases.

{
    "ok": true,
    "message": "Query executed, 1 row affected",
    "rowcount": 1,
    "rows": [],
    "truncated": false,
    "analysis": [
        {
            "operation": "insert",
            "database": "data",
            "table": "dogs",
            "required_permission": "insert-row, update-row, delete-row",
            "source": null
        }
    ]
}

If SQLite reports -1 for the row count, the message will be "Query executed".

For most write statements "rows" will be an empty list and "truncated" will be false. If the SQL uses SQLite's RETURNING clause, "rows" will contain returned rows using the same default representation as table and query JSON responses. "truncated" indicates if more rows were returned than the execute-write returning row limit, which defaults to 10:

{
    "ok": true,
    "message": "Query executed, 1 row affected",
    "rowcount": 1,
    "rows": [
        {
            "id": 1,
            "name": "Cleo"
        }
    ],
    "truncated": false,
    "analysis": [
        {
            "operation": "insert",
            "database": "data",
            "table": "dogs",
            "required_permission": "insert-row, update-row, delete-row",
            "source": null
        },
        {
            "operation": "read",
            "database": "data",
            "table": "dogs",
            "required_permission": "view-table",
            "source": null
        }
    ]
}

Errors use the standard Datasette error format:

{
    "ok": false,
    "error": "Permission denied: need execute-write-sql",
    "errors": [
        "Permission denied: need execute-write-sql"
    ],
    "status": 403
}

Inserting rows

This requires the insert-row permission.

A single row can be inserted using the "row" key:

POST /<database>/<table>/-/insert
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "row": {
        "column1": "value1",
        "column2": "value2"
    }
}

Column values can use the binary value JSON format to write BLOB data.

If successful, this will return a 201 status code and the newly inserted row, for example:

{
    "rows": [
        {
            "id": 1,
            "column1": "value1",
            "column2": "value2"
        }
    ],
    "row_paths": ["1"]
}

row_paths has the path of each returned row, in the same order, as used in its row page URL and by the row_paths table extra: /<database>/<table>/1 here. A row with a null primary key has no row page, so its path is null.

To insert multiple rows at a time, use the same API method but send a list of dictionaries as the "rows" key:

POST /<database>/<table>/-/insert
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "rows": [
        {
            "column1": "value1",
            "column2": "value2"
        },
        {
            "column1": "value3",
            "column2": "value4"
        }
    ]
}

If successful, this will return a 201 status code and a {"ok": true} response body.

The maximum number rows that can be submitted at once defaults to 100, but this can be changed using the max_insert_rows setting.

To return the newly inserted rows, add the "return": true key to the request body:

{
    "rows": [
        {
            "column1": "value1",
            "column2": "value2"
        },
        {
            "column1": "value3",
            "column2": "value4"
        }
    ],
    "return": true
}

This will return the same "rows" and "row_paths" keys as the single row example above. There is a small performance penalty for using this option.

If the table does not have an explicit primary key, each returned row will include the rowid that SQLite assigned to it. You can also set the rowid yourself by including it as a key in the row.

If any of your rows have a primary key that is already in use, you will get an error and none of the rows will be inserted:

{
    "ok": false,
    "error": "UNIQUE constraint failed: new_table.id",
    "errors": [
        "UNIQUE constraint failed: new_table.id"
    ],
    "status": 400
}

Pass "ignore": true to ignore these errors and insert the other rows:

{
    "rows": [
        {
            "id": 1,
            "column1": "value1",
            "column2": "value2"
        },
        {
            "id": 2,
            "column1": "value3",
            "column2": "value4"
        }
    ],
    "ignore": true
}

The response then says how many of the rows were inserted and how many were ignored:

{
    "ok": true,
    "inserted": 1,
    "ignored": 1
}

Or you can pass "replace": true to replace any rows with conflicting primary keys with the new values. This requires the update-row permission.

Pass "alter: true to automatically add any missing columns to the table. This requires the alter-table permission.

Inserting many rows in a compact form

Larger batches of rows can name their columns once, in a columns list, with each of the rows as a list of values in the same order:

{
    "columns": ["id", "column1", "column2"],
    "rows": [
        [1, "value1", "value2"],
        [2, "value3", "value4"]
    ]
}
  • The max_insert_rows limit does not apply to this form. The number of rows is limited by the size of the request body, 10MB unless the max_post_body_bytes setting has changed it.

  • All of the rows in a request are inserted in one transaction: if any of them fails, none are inserted.

  • Every row must have exactly one value for each of the columns. Use null for a missing value.

  • "ignore", "replace", "alter" and "return" work as they do for a list of objects. "row" cannot be used with "columns".

  • Values can use the binary value JSON format.

The upsert API accepts the same form. The columns must include the table's primary key columns.

Datasette's own dialogs for importing CSV and TSV files use this form.

Linking a new row to other rows

The m2m key inserts a row along with its many-to-many links, in one transaction. It maps relationship names to the body that the link API takes for that relationship, usually an add list:

{
    "row": {"title": "Alien"},
    "m2m": {
        "movie_tags": {"add": [5, {"create": {"tag": "noir"}}]},
        "movie_actors": {"add": [{"value": 3, "through": {"role": "Lead"}}]}
    }
}
  • The row is inserted, then each relationship's links are written, in the order given. If anything fails, nothing is inserted.

  • m2m can only be used when inserting exactly one row, and not with "ignore": true, "replace": true or the upsert API.

  • All of the relationships together can have at most 1,000 add, update and remove items, the same limit as the link API. A request with more is a 400 error, such as A request can have at most 1000 add, update and remove items in all, got 1001.

  • Everything else is as described for the link API: the values to link must exist, required extra columns must be given values, and so on.

The response gains an m2m object with, for each relationship, what the link API returns for it.

Everything that can be checked is checked before anything is written, and every error found is returned. Errors about a relationship start with m2m.<name>::

{
    "ok": false,
    "error": "m2m.movie_actors: Unknown column for movie_actors: rol. Its extra columns are: role; m2m.nope: Invalid _m2m: nope is not a many-to-many table for movies",
    "errors": [
        "m2m.movie_actors: Unknown column for movie_actors: rol. Its extra columns are: role",
        "m2m.nope: Invalid _m2m: nope is not a many-to-many table for movies"
    ],
    "status": 400
}

The status is 403 if any of them is a permission error, otherwise 400. Errors found while writing roll back the whole request and are reported in the same way.

This needs insert-row and view-table on the table, plus the permissions the link API needs for each relationship. The row's insert-rows event is recorded first, then the link API's events for each relationship.

Upserting rows

An upsert is an insert or update operation. If a row with a matching primary key already exists it will be updated - otherwise a new row will be inserted.

The upsert API is mostly the same shape as the insert API. It requires both the insert-row and update-row permissions.

It also accepts the same binary value JSON format.

POST /<database>/<table>/-/upsert
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "rows": [
        {
            "id": 1,
            "title": "Updated title for 1",
            "description": "Updated description for 1"
        },
        {
            "id": 2,
            "description": "Updated description for 2",
        },
        {
            "id": 3,
            "title": "Item 3",
            "description": "Description for 3"
        }
    ]
}

Imagine a table with a primary key of id and which already has rows with id values of 1 and 2.

The above example will:

  • Update the row with id of 1 to set both title and description to the new values

  • Update the row with id of 2 to set title to the new value - description will be left unchanged

  • Insert a new row with id of 3 and both title and description set to the new values

Similar to /-/insert, a row key with an object can be used instead of a rows array to upsert a single row.

The compact form, a columns list with each of the rows as a list of values, can be used here too.

If successful, this will return a 200 status code and a {"ok": true} response body. This is deliberately different from the 201 returned by insert: an upsert may update existing rows without creating anything, so it does not claim resource creation.

Add "return": true to the request body to return full copies of the affected rows after they have been inserted or updated:

{
    "rows": [
        {
            "id": 1,
            "title": "Updated title for 1",
            "description": "Updated description for 1"
        },
        {
            "id": 2,
            "description": "Updated description for 2",
        },
        {
            "id": 3,
            "title": "Item 3",
            "description": "Description for 3"
        }
    ],
    "return": true
}

This will return the following:

{
    "ok": true,
    "rows": [
        {
            "id": 1,
            "title": "Updated title for 1",
            "description": "Updated description for 1"
        },
        {
            "id": 2,
            "title": "Item 2",
            "description": "Updated description for 2"
        },
        {
            "id": 3,
            "title": "Item 3",
            "description": "Description for 3"
        }
    ],
    "row_paths": ["1", "2", "3"]
}

When using upsert you must provide the primary key column (or columns if the table has a compound primary key) for every row, or you will get a 400 error:

{
    "ok": false,
    "error": "Row 0 is missing primary key column(s): \"id\"",
    "errors": [
        "Row 0 is missing primary key column(s): \"id\""
    ],
    "status": 400
}

If your table does not have an explicit primary key you should pass the SQLite rowid key instead.

Pass "alter: true to automatically add any missing columns to the table. This requires the alter-table permission.

Updating a row

To update a row, make a POST to /<database>/<table>/<row-pks>/-/update. This requires the update-row permission.

POST /<database>/<table>/<row-pks>/-/update
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "update": {
        "text_column": "New text string",
        "integer_column": 3,
        "float_column": 3.14
    }
}

<row-pks> here is the tilde-encoded primary key value of the row to update - or a comma-separated list of primary key values if the table has a composite primary key.

You only need to pass the columns you want to update. Any other columns will be left unchanged.

Updated values can use the binary value JSON format.

If successful, this will return a 200 status code and a {"ok": true} response body.

Add "return": true to the request body to return the updated row:

{
    "update": {
        "title": "New title"
    },
    "return": true
}

The returned JSON will look like this:

{
    "ok": true,
    "rows": [
        {
            "id": 1,
            "title": "New title",
            "other_column": "Will be present here too"
        }
    ]
}

Any errors will use the standard error format, with a 400 status code for a bad input or a 403 status code for an authentication or permission error.

Pass "alter: true to automatically add any missing columns to the table. This requires the alter-table permission.

Deleting a row

To delete a row, make a POST to /<database>/<table>/<row-pks>/-/delete. This requires the delete-row permission.

POST /<database>/<table>/<row-pks>/-/delete
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>

<row-pks> here is the tilde-encoded primary key value of the row to delete - or a comma-separated list of primary key values if the table has a composite primary key.

If successful, this will return a 200 status code and a {"ok": true} response body.

Any errors will use the standard error format, with a 400 status code for a bad input or a 403 status code for an authentication or permission error.

Datasette does not turn on SQLite's foreign key enforcement, so deleting a row does not delete rows in other tables that reference it, even if their foreign keys use ON DELETE CASCADE. Those rows are left pointing at the deleted row's old ID, which SQLite can give to a row inserted later. The optional request body described below can also delete the row's many-to-many links and clear the foreign keys of other rows that reference it, in the same transaction as the row.

The body is optional. To delete links or clear references along with the row, send a JSON object with delete_m2m, clear_references or both; any other key is a 400 error. Send it as application/json: a body with that content type must be valid JSON. A request with no body, or a form body, deletes just the row.

Here is a request that deletes a movie, its links to people through movie_actors and movie_crew, and keeps its reviews and trailers, clearing their movie_id:

POST /m2m/movies/41/-/delete
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "delete_m2m": ["movie_actors", "movie_crew"],
    "clear_references": ["reviews.movie_id", "trailers.movie_id"]
}

The response says how many junction table rows were deleted for each relationship, and how many rows were changed for each reference:

{
    "ok": true,
    "m2m_deleted": {
        "movie_actors": 9,
        "movie_crew": 4
    },
    "references_cleared": {
        "reviews.movie_id": 3,
        "trailers.movie_id": 1
    }
}

m2m_deleted is only included if the request has delete_m2m, and references_cleared only if it has clear_references. Without either key the response is {"ok": true}.

Everything happens in one transaction: the links are deleted and the references cleared, then the row is deleted. Every check is made before anything is written, and if any part fails nothing is changed.

To see what points at a row before deleting it, request the row JSON with ?_extra=m2m,foreign_key_tables,foreign_key_details&_m2m_size=0, as the row delete dialog does. m2m lists the row's relationships and their counts, foreign_key_tables counts the rows in each table that reference it, and foreign_key_details says, for each of those foreign keys, whether it can be cleared and the reference name to pass to clear_references. Match the items of the last two on other_table and other_column. Each extra is described in full under Row JSON responses.

Clearing references to a row along with it

clear_references keeps the rows in other tables that reference the row, and sets their foreign key to null. It is a list of table.column names, such as reviews.user_id: the reference names given by the foreign_key_details row extra.

Pass each reference back exactly as the extra gives it. These names are not tilde-encoded, and each one is matched as a whole string rather than split at its dot, so a table or column whose name contains a dot works: a by.user column of an old.logs table is old.logs.by.user. The names in delete_m2m are different: they are relationship names, in which a full stop in a table or column name is tilde-encoded.

A column can only be cleared if it can be null and is not the junction table column of a relationship that delete_m2m deletes. Its table needs the update-row permission.

Errors are 400 for a value that is not a list of names, a name that is not a foreign key referencing the table, or a column that cannot be cleared (Cannot clear badges.user_id: it is NOT NULL), and 403 without the permission or for an immutable database.

Each changed row records an update-row event.

Listing a table's many-to-many relationships

GET /<database>/<table>/-/m2m lists the junction tables that give a table its many-to-many relationships, with the number of links in each. This is what the Relationships section of the alter table dialog shows. It includes the junction tables of relationships that the m2m table configuration does not show.

GET /m2m/movies/-/m2m
{
    "ok": true,
    "database": "m2m",
    "table": "movies",
    "primary_keys": ["id"],
    "m2m_config": null,
    "can_create": true,
    "junctions": [
        {
            "junction": "movie_tags",
            "junction_url": "/m2m/movie_tags",
            "other_table": "tags",
            "self_referential": false,
            "links": 93,
            "links_capped": false,
            "links_timed_out": false,
            "junction_kind": "plain",
            "extra_columns": [],
            "displayed": true,
            "can_remove": true,
            "relationships": [
                {
                    "name": "movie_tags",
                    "label": "tags",
                    "junction": "movie_tags",
                    "junction_url": "/m2m/movie_tags",
                    "table": "tags",
                    "column": "tag_id",
                    "other_column": "id",
                    "near_column": "movie_id",
                    "label_column": "tag",
                    "label_template": null,
                    "can_add": true,
                    "can_remove": true,
                    "can_update": true,
                    "can_create": true,
                    "create_label_column": "tag",
                    "extra_columns": [],
                    "unique_pair": true,
                    "junction_kind": "plain",
                    "pill_columns": [],
                    "pill_columns_more": 0,
                    "pill_columns_error": null,
                    "other_column_is_pk": true,
                    "autocomplete_url": "/m2m/tags/-/autocomplete",
                    "displayed": true
                }
            ]
        }
    ]
}

Each junction table is listed once, with the relationships through it in relationships, in the format of the m2m extra without its rows, plus displayed. A self-referential junction table has two relationships, one for each direction.

  • links is the number of rows in the junction table, counted up to 10,000. links_capped is true if there are more than that. If counting takes longer than facet_time_limit_ms, links is null and links_timed_out is true.

  • extra_columns lists the names of the junction table's extra columns.

  • displayed is false for relationships that the table's pages do not show, because the m2m table configuration lists the table's relationships and does not include them. m2m_config is "list" for a table with a list like that, "off" for m2m: false and null otherwise.

  • can_remove is true if the actor can remove the relationship with the drop_m2m operation of the alter table API: the junction table must be a plain junction table or a junction table with extra columns (How relationships are detected), and the actor needs drop-table on it. junction_kind is plain, extra_columns or repeatable; a repeatable junction table cannot be removed this way.

  • can_create is true if the actor can create relationships with the add_m2m operation of the alter table API, which needs create-table. To suggest a junction table name that is not taken, a client can look up candidate names one at a time with the table schema JSON, /<database>/<name>/-/schema.json: a 404 means there is no table or view with that name. A table the actor cannot view gives a 403, and indexes and triggers are not tables, so a client that leaves name out of the add_m2m operation lets the server choose a name that is free.

This requires the view-table permission on the table, and only lists junction tables and related tables the actor can view.

Creating a table

To create a table, make a POST to /<database>/-/create. This requires the create-table permission.

POST /<database>/-/create
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "table": "name_of_new_table",
    "columns": [
        {
            "name": "id",
            "type": "integer"
        },
        {
            "name": "title",
            "type": "text",
            "not_null": true,
            "default": "Untitled"
        },
        {
            "name": "created",
            "type": "text",
            "default_expr": "current_timestamp"
        }
    ],
    "pk": "id"
}

The JSON here describes the table that will be created:

  • table is the name of the table to create. This field is required.

  • columns is a list of columns to create. Each column is a dictionary with name and type keys.

    • name is the name of the column. This is required.

    • type is the type of the column. This is optional - if not provided, text will be assumed. The valid types are text, integer, float and blob.

    • not_null can be set to true to create this column with a NOT NULL constraint.

    • default can be used to set a literal default value for this column.

    • default_expr can be used instead of default to set a SQLite default expression. See default_expr values.

    • fk_table can be used to create a single-column foreign key constraint referencing another table. fk_column is optional and can be used to specify the referenced column - if omitted, Datasette will use the single primary key of fk_table. Datasette creates an index on each foreign key column, named idx_<table>_<column>, unless the column is the table's primary key or already starts an index.

  • pk is the primary key for the table. This is optional - if not provided, Datasette will create a SQLite table with a hidden rowid column.

    If the primary key is an integer column, it will be configured to automatically increment for each new record.

    If you set this to id without including an id column in the list of columns, Datasette will create an auto-incrementing integer ID column for you.

  • pks can be used instead of pk to create a compound primary key. It should be a JSON list of column names to use in that primary key.

    Primary key columns are created as NOT NULL, because SQLite would otherwise allow rows with a null primary key. The exception is a single integer primary key, which SQLite never allows to be null. This also applies to tables created from example rows.

  • ignore can be set to true to ignore existing rows by primary key if the table already exists.

  • replace can be set to true to replace existing rows by primary key if the table already exists. This requires the update-row permission.

  • alter can be set to true if you want to automatically add any missing columns to the table. This requires the alter-table permission.

  • m2m can be a list of many-to-many relationships to create along with the new table, up to 20 of them. Each item is an object in the format of the args of an add_m2m operation of the alter table API, such as {"other_table": "tags"} or {"new_table": {"table": "authors"}}. An item can name the new table itself as its other_table, to link it to itself. The new table must have a single-column primary key. Everything is created in the same transaction as the table, so if any relationship cannot be created nothing is created, and the error says which item failed, for example m2m.1: Table not found: nope. The response then has created_tables and m2m keys, as described for the alter table API, with the new table first in created_tables. Creating relationships needs the same permissions as there. m2m cannot be used if the table already exists.

default_expr accepts these values:

Value

Recommended column type

Example inserted value

current_timestamp

text

2026-05-01 13:34:00

current_date

text

2026-05-01

current_time

text

13:34:00

current_unixtime

integer

1777642440

current_unixtime_ms

integer

1777642440000

This example creates a foreign key from projects.owner_id to the single primary key of owners:

{
    "table": "projects",
    "columns": [
        {
            "name": "id",
            "type": "integer"
        },
        {
            "name": "owner_id",
            "type": "integer",
            "fk_table": "owners"
        },
        {
            "name": "title",
            "type": "text"
        }
    ],
    "pk": "id"
}

If the table is successfully created this will return a 201 status code and the following response:

{
    "ok": true,
    "database": "data",
    "table": "name_of_new_table",
    "table_url": "http://127.0.0.1:8001/data/name_of_new_table",
    "table_api_url": "http://127.0.0.1:8001/data/name_of_new_table.json",
    "schema": "CREATE TABLE [name_of_new_table] (\n   [id] INTEGER PRIMARY KEY,\n   [title] TEXT NOT NULL DEFAULT 'Untitled',\n   [created] TEXT DEFAULT CURRENT_TIMESTAMP\n)"
}

Creating a table from example data

Instead of specifying columns directly you can instead pass a single example row or a list of rows. Datasette will create a table with a schema that matches those rows and insert them for you:

POST /<database>/-/create
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "table": "creatures",
    "rows": [
        {
            "id": 1,
            "name": "Tarantula"
        },
        {
            "id": 2,
            "name": "Kākāpō"
        }
    ],
    "pk": "id"
}

Example rows can use the binary value JSON format, allowing Datasette to infer BLOB columns.

The maximum number of rows that can be submitted at once defaults to 100, the same limit as the insert API, and can be changed using the max_insert_rows setting. A request with more rows than that is a 400 error, and no table is created. To create a table with more rows, create it and then add the remaining rows using the insert API.

Doing this requires both the create-table and insert-row permissions.

The 201 response here will be similar to the columns form, but will also include the number of rows that were inserted as row_count:

{
    "ok": true,
    "database": "data",
    "table": "creatures",
    "table_url": "http://127.0.0.1:8001/data/creatures",
    "table_api_url": "http://127.0.0.1:8001/data/creatures.json",
    "schema": "CREATE TABLE [creatures] (\n   [id] INTEGER PRIMARY KEY,\n   [name] TEXT\n)",
    "row_count": 2
}

You can call the create endpoint multiple times for the same table provided you are specifying the table using the rows or row option. New rows will be inserted into the table each time. This means you can use this API if you are unsure if the relevant table has been created yet.

If you pass a row to the create endpoint with a primary key that already exists you will get an error that looks like this:

{
    "ok": false,
    "error": "UNIQUE constraint failed: creatures.id",
    "errors": [
        "UNIQUE constraint failed: creatures.id"
    ],
    "status": 400
}

You can avoid this error by passing the same "ignore": true or "replace": true options to the create endpoint as you can to the insert endpoint.

To use the "replace": true option you will also need the update-row permission.

Pass "alter": true to automatically add any missing columns to the existing table that are present in the rows you are submitting. This requires the alter-table permission.

Database foreign key targets

The /<database>/-/foreign-key-targets endpoint returns the list of tables in a database that can be referenced by a single-column foreign key. This requires the create-table permission.

GET /<database>/-/foreign-key-targets

The response includes only tables with exactly one primary key column. Hidden tables, tables with compound primary keys and tables with no explicit primary key are omitted.

Each target includes the normalized SQLite type affinity for the primary key column in type. The type is calculated using SQLite's documented affinity rules: INT maps to integer; CHAR, CLOB or TEXT maps to text; BLOB or no type maps to blob; REAL and floating-point declared types map to real; everything else maps to numeric.

{
    "ok": true,
    "database": "data",
    "targets": [
        {
            "fk_table": "owners",
            "fk_column": "id",
            "type": "integer"
        },
        {
            "fk_table": "categories",
            "fk_column": "slug",
            "type": "text"
        }
    ]
}

Table foreign key suggestions

The /<database>/<table>/-/foreign-key-suggestions endpoint suggests possible single-column foreign key relationships for a table. This requires the alter-table permission.

GET /<database>/<table>/-/foreign-key-suggestions

The response includes every type-compatible single-column primary key target for each column in options. Datasette also performs a bounded data check against up to 500 rows in the table: if the sampled non-null values for a column all exist in a target primary key, that target is included in suggestions.

If the bounded check takes too long, the endpoint fails open. It still returns the type-compatible options for each column, but row_check.status will be "timed_out" and there may be no suggestions.

{
    "ok": true,
    "database": "data",
    "table": "projects",
    "row_check": {
        "attempted": true,
        "status": "completed",
        "row_limit": 500,
        "sampled_rows": 3,
        "checked_options": 4
    },
    "columns": [
        {
            "column": "owner_id",
            "type": "INTEGER",
            "affinity": "integer",
            "current": null,
            "suggestions": [
                {
                    "fk_table": "owners",
                    "fk_column": "id",
                    "confidence": "sampled",
                    "sampled_values": 3,
                    "reasons": [
                        "type_match",
                        "sample_values_exist",
                        "name_match"
                    ]
                }
            ],
            "options": [
                {
                    "fk_table": "owners",
                    "fk_column": "id",
                    "type": "INTEGER"
                }
            ]
        }
    ]
}

Altering tables

To alter an existing table, make a POST to /<database>/<table>/-/alter. This requires the alter-table permission, except for requests that only add or remove many-to-many relationships.

POST /<database>/<table>/-/alter
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>

The request body should include an operations array. Each operation has the same top-level shape: an op string and an args object.

{
    "operations": [
        {
            "op": "add_column",
            "args": {
                "name": "slug",
                "type": "text",
                "not_null": true,
                "default": ""
            }
        },
        {
            "op": "add_column",
            "args": {
                "name": "created",
                "type": "text",
                "default_expr": "current_timestamp"
            }
        },
        {
            "op": "rename_column",
            "args": {
                "name": "title",
                "to": "headline"
            }
        },
        {
            "op": "rename_table",
            "args": {
                "to": "published_posts"
            }
        },
        {
            "op": "alter_column",
            "args": {
                "name": "score",
                "type": "float"
            }
        },
        {
            "op": "drop_column",
            "args": {
                "name": "draft_notes"
            }
        },
        {
            "op": "set_primary_key",
            "args": {
                "columns": ["id"]
            }
        },
        {
            "op": "add_foreign_key",
            "args": {
                "column": "owner_id",
                "fk_table": "owners"
            }
        },
        {
            "op": "drop_foreign_key",
            "args": {
                "column": "old_owner_id"
            }
        },
        {
            "op": "set_foreign_keys",
            "args": {
                "foreign_keys": [
                    {
                        "column": "owner_id",
                        "fk_table": "owners",
                        "fk_column": "id"
                    }
                ]
            }
        },
        {
            "op": "reorder_columns",
            "args": {
                "columns": ["id", "headline", "slug", "created", "score"]
            }
        }
    ]
}

Supported operations:

  • add_column adds a new column. args accepts name, optional type of text, integer, float or blob, optional not_null, optional literal default and optional default_expr. If not_null is true either a non-null default or default_expr is required.

  • rename_column renames a column. args accepts name and to.

  • rename_table renames the table. args accepts to, the new table name. If combined with other operations, Datasette applies the column, primary key, foreign key and column order changes before renaming the table.

  • alter_column changes column properties. args accepts name and at least one of type, not_null, literal default or default_expr. Passing "default": null removes an existing default.

  • drop_column drops a column. args accepts name.

  • set_primary_key changes the table primary key. args accepts columns, a list of one or more column names.

  • add_foreign_key adds a single-column foreign key constraint. args accepts column, fk_table and optional fk_column. If fk_column is omitted, Datasette will use the single primary key of fk_table.

  • drop_foreign_key removes the foreign key constraint for a column. args accepts column.

  • set_foreign_keys replaces all foreign key constraints on the table. args accepts foreign_keys, a list of objects that each have column, fk_table and optional fk_column. An empty list removes all foreign key constraints.

    Each new foreign key that add_foreign_key or set_foreign_keys adds gets an index on its column named idx_<table>_<column>, unless the column is the table's primary key or already starts an index, as with the create table API. Foreign keys the table already had are left as they are, even if set_foreign_keys lists them again. Removing a foreign key constraint keeps the column, and any index on it.

  • reorder_columns reorders columns. args accepts columns, a list of one or more column names. Columns omitted from this list will appear afterwards in their existing order.

  • add_m2m creates a many-to-many relationship between this table and another table, by creating a junction table. args accepts other_table or new_table, and an optional junction table name. See Adding and removing relationships while altering a table.

  • drop_m2m removes a many-to-many relationship by dropping its junction table. args accepts junction, the name of a plain junction table or a junction table with extra columns (How relationships are detected) of this table.

default is always treated as a literal value. default_expr accepts the values shown in default_expr values and is rendered as the corresponding SQLite default expression.

For foreign key operations that omit fk_column, the referenced fk_table must have a single-column primary key. Datasette will return an error if it cannot identify a single primary key column for that table.

add_column, rename_table and the many-to-many operations change the table in place, using ALTER TABLE. Every other change rebuilds the table: a new table is created, the rows are copied into it, the old table is dropped and the new one is renamed. add_column also rebuilds the table if the column has a default or default_expr and is not not_null: the column is added in place and the rebuild then sets its default. An add_column with not_null and a literal default is done in place. One with not_null and a default_expr cannot be done at all, because SQLite cannot add a column whose default is not a constant, such as CURRENT_TIMESTAMP, to a table that has rows (or, in older versions of SQLite, to any table): the request fails with Cannot add a column with non-constant default. A request that combines operations is rebuilt once if any of them needs it.

Two of these steps depend on the version of SQLite:

  • Before SQLite 3.26.0 a table that a view refers to cannot be rebuilt. A request that needs a rebuild, including an add_column with a default as described above, fails with an error such as error in view movies_view: no such table: main.movies and nothing is changed. Changes made in place, such as an add_column without a default, still work.

  • Before SQLite 3.26.0 rename_table only updates the foreign keys in other tables that reference the table if PRAGMA foreign_keys is on. Otherwise they are left pointing at the old name.

A successful response returns the new schema and the previous schema. If the request used rename_table, table, table_url and table_api_url will use the new table name. Renaming a table through this endpoint triggers the RenameTableEvent event.

{
    "ok": true,
    "database": "data",
    "table": "published_posts",
    "table_url": "http://127.0.0.1:8001/data/published_posts",
    "table_api_url": "http://127.0.0.1:8001/data/published_posts.json",
    "altered": true,
    "schema": "CREATE TABLE ...",
    "before_schema": "CREATE TABLE ...",
    "operations_applied": 11
}

Any errors will use the standard error format, with a 400 status code for a bad input or a 403 status code for an authentication or permission error.

Adding and removing relationships while altering a table

The add_m2m and drop_m2m operations change a table's many-to-many relationships in the same request, and the same transaction, as its columns. If any part of the request fails, nothing is changed: no columns are altered and no tables are created or dropped. This is what the alter table dialog sends.

{
    "operations": [
        {
            "op": "add_column",
            "args": {"name": "year", "type": "integer"}
        },
        {
            "op": "add_m2m",
            "args": {"other_table": "tags"}
        },
        {
            "op": "add_m2m",
            "args": {
                "new_table": {
                    "table": "awards",
                    "label_column": "name"
                },
                "name": "movie_awards"
            }
        },
        {
            "op": "drop_m2m",
            "args": {"junction": "movie_actors"}
        }
    ]
}

Whatever order they are listed in, the junction tables named by drop_m2m are dropped first, then the other operations are applied to the table, and then the add_m2m relationships are created, for the table under its new name if it is renamed. Each operation is checked before anything is written, and errors name the operation, for example operations.1: Table not found: tags.

The args of an add_m2m operation describe one relationship, and must have exactly one of other_table and new_table:

  • other_table is an existing table to link to. It can be the table itself, for a self-referential relationship. Both tables must have a single-column primary key.

  • new_table creates the other table at the same time, for example {"table": "awards", "label_column": "name"}. The new table has an id integer primary key and a text column named label_column, which defaults to name and is used as its label column.

  • name, the name of the junction table, is optional. It defaults to the names of the two tables joined by _ in alphabetical order, such as movies_tags, with _2, _3 and so on added if that name is taken by any table, view, index or trigger. A name that is given must not exist already: the error says what has that name.

For {"other_table": "tags"} on movies this creates a plain junction table, with an index for looking up links from the other side. Creating and removing relationships describes how its name, columns and index are chosen.

CREATE TABLE movies_tags (
   movies_id INTEGER NOT NULL REFERENCES movies(id),
   tags_id INTEGER NOT NULL REFERENCES tags(id),
   PRIMARY KEY (movies_id, tags_id)
);
CREATE INDEX idx_movies_tags_tags_id ON movies_tags (tags_id);

A request can have up to 20 add_m2m operations.

drop_m2m drops the junction table, deleting all of its links along with the values of any extra columns. Only plain junction tables and junction tables with extra columns (How relationships are detected) of this table can be dropped this way, since the rows of repeatable junction tables hold data of their own. Use the drop table API to drop one of those, or to find out how many rows a junction table has before dropping it.

A request with only add_m2m and drop_m2m operations does not need alter-table, since it does not change the table itself. It needs view-table on the table. Each add_m2m needs create-table on the database and view-table on the other table, and each drop_m2m needs drop-table and view-table on the junction table. An actor who can create tables does not need to be able to view the new junction table: the relationship is still created, but m2m in the response leaves out relationships the actor cannot view.

The response has these extra keys when the request has relationship operations:

  • created_tables and dropped_tables list the tables that were created and dropped. A new_table is listed before its junction table.

  • m2m describes the new relationships, keyed by relationship name, in the format of the relationships of the relationships API. A self-referential junction table has two relationships, one in each direction.

  • m2m_config is "list" or "off" if the table's m2m table configuration lists its relationships or turns them off, and null otherwise. New relationships are then not shown on the table's pages until they are added to that list, and their displayed is false.

  • m2m_dropped has the junction, row_count (the number of rows deleted) and relationships (the names of the relationships removed, two for a self-referential junction table) of each junction table that was dropped.

  • altered is false if the table's own schema did not change.

{
    "ok": true,
    "database": "m2m",
    "table": "movies",
    "altered": true,
    "created_tables": ["movies_tags", "awards", "movie_awards"],
    "dropped_tables": ["movie_actors"],
    "m2m_config": null,
    "m2m": {
        "movies_tags": {"name": "movies_tags", "displayed": true},
        "movie_awards": {"name": "movie_awards", "displayed": true}
    },
    "m2m_dropped": [
        {
            "junction": "movie_actors",
            "row_count": 2400,
            "relationships": ["movie_actors"]
        }
    ]
}

The m2m entries are abbreviated here.

Errors for relationship operations use the standard error format, and nothing is changed:

  • 400 for args that are not in the format described above, a table that is a view or does not have a single-column primary key, a junction name or new_table that exists already, a drop_m2m table that is not a junction table of this table or is a repeatable junction table, or more than 20 add_m2m operations. An error for a name that is taken says what has it, such as a table named movies_tags already exists.

  • 403 for a missing permission, or if the database is immutable.

  • 404 if the table does not exist, or the other table does not exist or the actor cannot view it.

The request records a create-table event for each table created and a drop-table event for each junction table dropped, as well as an alter-table event if the table's own schema changed.

Setting a column type

To set a column type for a table column, make a POST to /<database>/<table>/-/set-column-type. This requires the set-column-type permission.

POST /<database>/<table>/-/set-column-type
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
    "column": "title",
    "column_type": {
        "type": "email"
    }
}

This will return a 200 response like this:

{
    "ok": true,
    "database": "data",
    "table": "posts",
    "column": "title",
    "column_type": {
        "type": "email",
        "config": null
    }
}

To provide column type configuration, include a config object:

{
    "column": "title",
    "column_type": {
        "type": "url",
        "config": {
            "max_length": 200
        }
    }
}

To clear an existing column type assignment, set column_type to null:

{
    "column": "title",
    "column_type": null
}

This API stores the assignment in Datasette's internal database, so it can be used with immutable databases as well as mutable ones.

Any errors will use the standard error format, with a 400 status code for a bad input or a 403 status code for an authentication or permission error.

Setting the label column

To set the label column of a table, make a POST to /<database>/<table>/-/set-label-column. This requires the set-label-column permission.

POST /<database>/<table>/-/set-label-column
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>

label_column can be a column name or a label template:

{
    "label_column": "{app_label}: {model}"
}

This will return a 200 response like this:

{
    "ok": true,
    "database": "data",
    "table": "django_content_type",
    "label_column": "{app_label}: {model}",
    "label": {
        "label_column": null,
        "label_template": "{app_label}: {model}",
        "source": "saved"
    }
}

label_column is the label that was saved, with column names spelled as they are in the table. label is the label the table now uses: label_column for a single column or label_template for a template, and its source, which is "saved", "configured" or "detected". label is null if the table has no label.

A saved label takes priority over the label_column table configuration. To remove it, so that the table uses its configured or detected label column again, set label_column to null:

{
    "label_column": null
}

This API stores the label in Datasette's internal database, so it can be used with immutable databases as well as mutable ones. It lasts across restarts only if the internal database is a file, see Datasette's internal database. If a column the saved label uses is later removed from the table, the label is ignored.

Any errors will use the standard error format, with a 400 status code for a label column that is not a column of the table, a template that cannot be parsed or a view, a 403 status code for an authentication or permission error, or a 404 if the table does not exist.

Dropping tables

To drop a table, make a POST to /<database>/<table>/-/drop. This requires the drop-table permission.

POST /<database>/<table>/-/drop
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>

Without a POST body this will return a status 200 with a note about how many rows will be deleted:

{
    "ok": true,
    "database": "<database>",
    "table": "<table>",
    "row_count": 5,
    "message": "Pass \"confirm\": true to confirm"
}

If you pass the following POST body:

{
    "confirm": true
}

Then the table will be dropped and a status 200 response of {"ok": true} will be returned.

confirm must be the JSON boolean true. "confirm": false returns the same response as no body. Any other value, such as "true", "no", 1 or null, is a 400 error, confirm must be true or false, and the table is not dropped.

Any errors will use the standard error format, with a 400 status code for a bad input or a 403 status code for an authentication or permission error.