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 queryanalyze/store/definitionendpoints,/-/query/parameters,/-/execute-write/analyzeand the JSON returned by the/-/permissionsdebug 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 thedebugandrequestextras.
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 alwaysfalsefor 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=SHAPEThe shape of the JSON to return, documented above.
?_nl=onWhen used with
?_shape=arrayproduces newline-delimited JSON objects.?_pretty=1Indents 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=COLUMN2If 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=onIf your data contains infinity or -infinity values, Datasette will replace them with None when returning them as JSON. If you pass
_json_infinity=1Datasette will instead return them asInfinityor-Infinitywhich is invalid JSON but can be processed by some custom JSON parsers.?_timelimit=MSSets 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=SECONDSFor how many seconds should this response be cached by HTTP proxies? Use
?_ttl=0to disable HTTP caching entirely for this request.?_trace=1Turns 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.
countTotal count of rows matching these filters (May execute additional queries.)
GET /fixtures/facetable.json?_extra=count15count_truncatedTrue 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_truncatedfalsecount_sqlSQL 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_resultsResults of facets calculated against this data. A dictionary with
resultsandtimed_outkeys:resultsmaps facet names to facet dictionaries withname,type,resultsand URL keys, and each facet result item includesvalue,label,countandtoggle_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_outList of names of facet calculations that exceeded the facet time limit.
GET /fixtures/facetable.json?_facet=state&_extra=facets_timed_outA 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_facetsSuggestions for facets that might return interesting results. Each item is a dictionary with
nameandtoggle_urlkeys, and may include extra keys such astypeorlabeldepending 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_enHuman-readable description of the filters
GET /fixtures/facetable.json?state=CA&_sort=pk&_extra=human_description_en"where state = \"CA\" sorted by pk"columnsList 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_columnsList 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_keysList 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_pathsThe path of each row in
rows, in the same order: the part of its row page URL after the table, such as3for/fixtures/facetable/3. A path is the row's primary key values, tilde-encoded and joined with commas, or itsrowidfor a table with no primary key, andnullfor a row with anullprimary key, which has no row page. The whole extra isnullfor views.GET /fixtures/compound_primary_key.json?_extra=row_paths[ "a,b", "a~2Fb,~2Ec-d", "d,e" ]
column_detailsSQLite schema details for columns in this table. The dictionary maps column names to objects describing the schema for each column. (Each object has
typeas the declared type string returned by SQLite, or""if no type was declared;sqlite_typeas the normalized SQLite affinity, one ofTEXT,INTEGER,REAL,BLOBorNUMERIC;notnullas a boolean;defaultas the raw SQL default expression string, such as"42","'hello'"or"datetime('now')", ornullif there is no default;is_pkas a boolean;pk_positionas the integer primary key position reported by SQLite, or0for columns that are not part of the primary key; andhiddenas the integer value reported by SQLite'sPRAGMA table_xinfo.hiddenis0for normal columns,1for hidden virtual table columns,2for virtual generated columns and3for 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_columnsColumn metadata used by the HTML table display. Each item includes
name,sortable,is_pk,type,notnull,description,column_type,column_type_configandhas_fkskeys.has_fksis 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_cellRendered HTML for each cell using the render_cell plugin hook (See the render_cell() plugin hook documentation.)
The
render_cellarray has one item per row, in the same order as therowsarray. 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>" } ] }
debugExtra 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 }
requestDictionary with request details:
url,path,full_path,hostandargswhereargsmaps 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" ] } }
queryDetails of the underlying SQL query as a dictionary with
sqlandparamskeys.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_typesColumn 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_typesThis example is from an instance where the
tagscolumn has been assigned thejsoncolumn type.{ "tags": { "type": "json", "config": null } }
set_column_type_uiInformation needed to build an interface for assigning column types, or
Noneif unavailable. When present it haspathandcolumnskeys;columnsmaps column names tocurrentandoptionsvalues. (nullunless 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-typepermission.currentis the column type currently assigned to each column andoptionslists 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_uiInformation needed to build an interface for setting the table's label column, or
Noneif unavailable. (nullunless 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-columnpermission.savedis the label column or template saved with the API,configuredis thelabel_columntable configuration,detectedis the label column Datasette detects.defaultis the label the table uses without a saved one, from its configuration if that can be used, otherwise the detected label column.currentis 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" ] }
metadataMetadata dictionary for the table, database or stored query. Table and row metadata include a
columnsdictionary 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=metadataThis example is from an instance where the
facetabletable has a metadatadescriptionand a column description for itsstatecolumn. Thecolumnsobject 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" } }
extrasList of
?_extra=blocks that can be used on this page. Each item hasname,description,toggle_urlandselectedkeys.Shape abbreviated from /fixtures/facetable.json?_extra=extras - the full response lists every extra described on this page.
toggle_urlis the current URL with that extra added or removed, andselectedistruefor 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 } ]
databaseDatabase name
GET /fixtures/facetable.json?_extra=database"fixtures"tableTable name
GET /fixtures/facetable.json?_extra=table"facetable"database_colorColor 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"renderersDictionary mapping output format names such as
jsonor plugin-provided renderer names to URLs for this data in that format.GET /fixtures/facetable.json?_extra=renderersEach 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_templatesList 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_resultsFacet result dictionaries sorted for display. Each item has the same shape as an entry from
facet_results['results']. (The same data asfacet_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_definitionSQL 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_definitionSQL 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_viewWhether this resource is a view instead of a table
GET /fixtures/simple_view.json?_extra=is_viewtrueprivateWhether this resource is private to the current actor (
trueif the current actor can see this resource but an anonymous user could not. See Permissions.)GET /fixtures/facetable.json?_extra=privatefalseexpandable_columnsList of foreign key columns that can be expanded with labels. Each item is a
(foreign_key, label_column)pair whereforeign_keyis the SQLite foreign key dictionary andlabel_columnis the label column in the referenced table, its label template if the label combines several columns, orNone. (See Expanding foreign key references for how to expand these labels.)GET /fixtures/facetable.json?_extra=expandable_columnsEach 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_columnsList of foreign key columns that have been expanded with labels on this page, using
?_labels=onor?_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_argsList 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" ] ]
m2mMany-to-many relationships for the rows on this page, through junction tables. Maps each relationship name to a description of it, such as its
junctiontable, relatedtable,extra_columnsand the actor'scan_addandcan_removepermissions, plusrowsmapping each row path to itstotaland up to?_m2m_size=relateditems. Each item haslinks, one for each junction table row, with itspath,urland the values of its extra columns asthrough, 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_throughWhen the table is filtered by exactly one
?_m2m.J=valuefilter, the junction table rows that link each row to that value, with the values of the junction table's extra columns, such as arole.relationshipis the name of the relationship,J, androwsmaps the path of each row on the page to itslinks, using the same row paths as them2mextra.linksis a list with one entry for each junction table row, with itspath,urland extra column values asthrough. A junction table that can link the same pair of rows more than once lists up to 10 of them, withlinks_truncatedset totrueif there are more. This extra isnullwithout exactly one?_m2m.J=valuefilter, or if the junction table has no extra columns. If reading the links runs out of therelationship_time_limit_msthat the request's relationships share, or fails, or SQLite lacks its JSON functions, it is{}and the response has anm2m_through_errormessage. (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.
columnsList of column names returned by this table, row or query.
GET /fixtures/simple_primary_key/1.json?_extra=columns[ "id", "content" ]
primary_keysList 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_detailsSQLite schema details for columns in this table. The dictionary maps column names to objects describing the schema for each column. (Each object has
typeas the declared type string returned by SQLite, or""if no type was declared;sqlite_typeas the normalized SQLite affinity, one ofTEXT,INTEGER,REAL,BLOBorNUMERIC;notnullas a boolean;defaultas the raw SQL default expression string, such as"42","'hello'"or"datetime('now')", ornullif there is no default;is_pkas a boolean;pk_positionas the integer primary key position reported by SQLite, or0for columns that are not part of the primary key; andhiddenas the integer value reported by SQLite'sPRAGMA table_xinfo.hiddenis0for normal columns,1for hidden virtual table columns,2for virtual generated columns and3for 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_cellRendered HTML for each cell using the render_cell plugin hook (See the render_cell() plugin hook documentation.)
The
render_cellobject is keyed by column name. Only columns whose rendered value differs from the default are included. If a?_shape=is specifiedrender_cellis instead a list with one item, matching therowslist.{ "row": { "id": 4, "content": "RENDER_CELL_DEMO" }, "render_cell": { "content": "<strong>Custom rendered HTML</strong>" } }
debugExtra 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" ] } }
requestDictionary with request details:
url,path,full_path,hostandargswhereargsmaps 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" ] } }
queryDetails of the underlying SQL query as a dictionary with
sqlandparamskeys.GET /fixtures/simple_primary_key/1.json?_extra=query{ "sql": "select * from simple_primary_key where \"id\"=:p0", "params": { "p0": "1" } }
column_typesColumn 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_typesThis example is from an instance where the
tagscolumn has been assigned thejsoncolumn type.{ "tags": { "type": "json", "config": null } }
metadataMetadata dictionary for the table, database or stored query. Table and row metadata include a
columnsdictionary 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=metadataThis table has no metadata, so only an empty
columnsobject is returned.{ "columns": {} }
extrasList of
?_extra=blocks that can be used on this page. Each item hasname,description,toggle_urlandselectedkeys.Shape abbreviated from /fixtures/facetable.json?_extra=extras - the full response lists every extra described on this page.
toggle_urlis the current URL with that extra added or removed, andselectedistruefor 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 } ]
databaseDatabase name
GET /fixtures/simple_primary_key/1.json?_extra=database"fixtures"tableTable name
GET /fixtures/simple_primary_key/1.json?_extra=table"simple_primary_key"database_colorColor 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"privateWhether this resource is private to the current actor (
trueif the current actor can see this resource but an anonymous user could not. See Permissions.)GET /fixtures/simple_primary_key/1.json?_extra=privatefalseforeign_key_tablesList of tables that link to this row using foreign keys. Each item includes the foreign key fields plus
countfor matching rows,count_cappedandlinkfor the filtered table URL. Eachcountstops at 10,000, withcount_cappedset totrueif there are more. The counts are subject to the facet_time_limit_ms time limit: if that is exceeded everycountisnull. (May execute additional queries.)GET /fixtures/simple_primary_key/1.json?_extra=foreign_key_tablescountis the number of rows in the other table that reference this row, andlinkis 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_detailsDetails of each foreign key that references this row, one item for each item in
foreign_key_tablesand in the same order, without the counts. Each item has the foreign key fields, thereferencename to pass to the row delete API'sclear_references, such asreviews.user_id, which is not tilde-encoded and is matched as a whole string, so pass it back exactly as given, the foreign key'son_deleteaction from the schema (NO ACTIONunless one is declared),can_clearandcannot_clear_reason:not nullable,part of primary key,permission(noupdate-rowon that table) orimmutable, ornullif it can be cleared.junctionistrueif 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'sdelete_m2mcan delete: a junction table whose links can be edited, or a relationship listed in them2mconfiguration. This does not depend on whether them2mconfiguration shows the relationship, or on SQLite's JSON functions. Those items also have the relationship name fordelete_m2masm2m, the related table asm2m_table, the junction table's foreign key to it asm2m_column,junction_kindandcan_remove, whether the actor can delete the junction table's rows. For other itemsjunctionisfalseand those keys arenull.junction_unknownistruefor every item if working out which tables are junction tables failed, in which case the error is logged and everyjunctionisfalse, even for a junction table, andfalseotherwise. Used by the row delete dialog, withforeign_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 } ]
m2mMany-to-many relationships for the rows on this page, through junction tables. Maps each relationship name to a description of it, such as its
junctiontable, relatedtable,extra_columnsand the actor'scan_addandcan_removepermissions, plusrowsmapping each row path to itstotaland up to?_m2m_size=relateditems. Each item haslinks, one for each junction table row, with itspath,urland the values of its extra columns asthrough, 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.
columnsList of column names returned by this table, row or query.
GET /fixtures/-/query.json?sql=select+1+as+one&_extra=columns[ "one" ]
render_cellRendered HTML for each cell using the render_cell plugin hook (See the render_cell() plugin hook documentation.)
The
render_cellarray has one item per query result row, in the same order as therowsarray. 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>" } ] }
debugExtra 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" } }
requestDictionary with request details:
url,path,full_path,hostandargswhereargsmaps 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" ] } }
queryDetails of the underlying SQL query as a dictionary with
sqlandparamskeys.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" } }
metadataMetadata dictionary for the table, database or stored query. Table and row metadata include a
columnsdictionary 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=metadataFor 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 }
extrasList of
?_extra=blocks that can be used on this page. Each item hasname,description,toggle_urlandselectedkeys.Shape abbreviated from /fixtures/facetable.json?_extra=extras - the full response lists every extra described on this page.
toggle_urlis the current URL with that extra added or removed, andselectedistruefor 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 } ]
databaseDatabase name
GET /fixtures/-/query.json?sql=select+1+as+one&_extra=database"fixtures"database_colorColor 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"privateWhether this resource is private to the current actor (
trueif 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=privatefalse
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=m2madds an"m2m"key describing each relationship, with the related rows of every row on the page. See The m2m extra.?_extra=m2m_throughadds 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=Nsets 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=0returns 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 them2mextra 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:
nameThe relationship name, used by the
?_m2m.NAME=filters and the write APIs.labelThe 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).junctionandjunction_urlThe 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.tableThe related table.
columnThe column in the junction table that points at the related table.
near_columnThe column in the junction table that points at this table.
other_columnThe column in the related table that
columnrefers to.other_column_is_pktrueifother_columnis the primary key of the related table.label_columnandlabel_templateThe label column of the related table, or
nullif it does not have one. If its label is a template that combines several columns,label_columnisnullandlabel_templateis the template, such as"{app_label}: {model}", otherwiselabel_templateisnull.autocomplete_urlThe autocomplete endpoint for searching the related table for rows to link, or
nullifother_columnis not its primary key.can_add,can_removeandcan_updateWhether 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
falsein an immutable database, and for a relationship through a repeatable junction table (junction_kindisrepeatable) unless the relationship is listed in the m2m table configuration.can_createandcreate_label_columncan_createistrueif 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_columnis the column that the label is for, the related table's label column, if rows can be created from a label, otherwisenull. Creating needscan_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 columnother_column, which is either anINTEGERprimary key that SQLite assigns or the label column itself (such as aslug 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_columnsThe 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'sname, its declaredtype(an empty string if it has none),notnull(trueif the column isNOT NULL),has_default(trueif it has a default value),default(the default as a SQL expression, ornull),sqlite_type(the type affinity, such asTEXT),column_type(an assigned column type as{"type", "config"}, ornull) andautocomplete_url(an autocomplete endpoint if the column is a foreign key to a table with a single-column primary key, otherwisenull). A column that isnotnullwithout a default must be given a value when a link is added.junction_kindThe kind of junction table:
plainfor a plain junction table,extra_columnsfor a junction table with extra columns, orrepeatablefor 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 them2mkey of the row APIs; the junction table's rows can still be changed with the ordinary row APIs.unique_pairtrueif the junction table can link a pair of rows only once: its primary key, or a unique index without awhereclause, is exactly the two foreign key columns, in either order. If it isfalsethe 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_moreandpill_columns_errorpill_columnslists 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_moreis the number of the junction table's other extra columns, which the pills show as "+N" after the values:2formovie_crew (movie_id, person_id, job, department, credited)configured to show justjob. It is0whenpill_columnsis configured asfalseor[], or could not be used. A link gets a right half in its pill if it has a non-empty value in one of thepill_columns, or ifpill_columns_moreis not0. The tooltip of that right half lists every value in the link'sthrough.pill_columns_erroris a message saying why thepill_columnsconfiguration of the relationship could not be used, such as an unknown column name, in which casepill_columnsis empty, otherwisenull.timed_outanderrortimed_outistrueif the query for this relationship ran out of the time left of relationship_time_limit_ms, which the relationships of a request share, anderroris an error message if the query failed. In both casesrowsis an empty object.rowsThe 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_pathsto?_extra=to get the path of each row inrows, 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) isnull, 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:
totalThe number of related rows, counted up to 10,000.
total_cappedtrueif there are more than 10,000 related rows, in which casetotalis10000.truncatedtrueifitemsdoes not include every related row.itemsUp to
?_m2m_size=related rows, in descending order ofvalue. Each has thevaluestored in the junction table, alabel, theurlof the related row and itslinks, described below. If the related table has no label column the label is the value as a string.urlThe URL of the related table filtered to just the rows related to this row, using a
?_m2m.filter.junction_rows_urlThe URL of the junction table filtered to the links of this row: the rows whose
near_columnholds 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.
Links¶
Each item's links is a list with one object for each link - each junction table row - between the two rows, usually just one. Relationships are only shown to actors who can view the junction table, so path and url are always included. Each link has these keys:
pathThe junction table row's path, as used in its row page URL: its primary key values, tilde-encoded and joined with commas, or its
rowidif the junction table has no primary key.urlThe URL of the junction table row's row page.
throughThe values of the junction table's extra columns for this link. Left out for a junction table with no extra columns.
truncated_columnsThe names of the columns in
throughwhose values were cut short, see Values that are cut short. Left out if none were.
Here is an item for a relationship whose junction table has an extra role column, from /m2m/movies/40.json?_extra=m2m:
{
"value": 175,
"label": "Guido Lee 175",
"url": "/m2m/people/175",
"links": [
{
"path": "40,175",
"url": "/m2m/movie_actors/40,175",
"through": {
"role": "Lead"
}
}
]
}
If unique_pair is false the related row can be linked more than once, and links has one object for each link, in primary key order. Here reviews is configured as a relationship, and user 1 reviewed this movie twice:
{
"value": 1,
"label": "user1",
"url": "/m2m/users/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."
}
}
]
}
Up to 10 links are returned for each related row. If there are more, the item also has "links_truncated": true and a links_url, the junction table filtered to every link between that pair, such as /fixtures/movie_actors?movie_id__exact=1&person_id__exact=7. The table and row pages show a "+ more" link to it after that row's pills. total, truncated and ?_m2m_size= count related rows, so user 1 above counts once.
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=valueor?_column=valueReturns 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(*)orsum(amount).?total=5returns rows wheretotalis the number5or the text"5". The same applies to__not,__inand__notin.?column__not=valueReturns rows where the column does not match the value.
?column__contains=valueRows where the string column contains the specified value (
column like "%value%"in SQL).?column__notcontains=valueRows where the string column does not contain the specified value (
column not like "%value%"in SQL).?column__endswith=valueRows where the string column ends with the specified value (
column like "%value"in SQL).?column__startswith=valueRows where the string column starts with the specified value (
column like "value%"in SQL).?column__gt=valueRows which are greater than the specified value.
?column__gte=valueRows which are greater than or equal to the specified value.
?column__lt=valueRows which are less than the specified value.
?column__lte=valueRows which are less than or equal to the specified value.
?column__like=valueMatch rows with a LIKE clause, case insensitive and with
%as the wildcard character.?column__notlike=valueMatch rows that do not match the provided LIKE clause.
?column__glob=valueSimilar to LIKE but uses Unix wildcard syntax and is case sensitive.
?column__in=value1,value2,value3Rows 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,value3Rows where column does not match any of the provided values. The inverse of
__in=. Also supports JSON arrays.?column__arraycontains=valueWorks 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
json1SQLite extension is enabled.?column__arraynotcontains=valueWorks 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
json1SQLite extension is enabled.?column__date=valueColumn is a datestamp occurring on the specified YYYY-MM-DD date, e.g.
2018-01-02.?column__isnull=1Matches rows where the column is null.
?column__notnull=1Matches rows where the column is not null.
?column__isblank=1Matches rows where the column is blank, meaning null or the empty string.
?column__notblank=1Matches rows where the column is not blank.
Special table arguments¶
?_col=COLUMN1&_col=COLUMN2List 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 asm2m:movie_actors, orref:and a table and column with a foreign key that points at this table, such asref: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 a400error. A column of the table whose name looks like a relationship column, such asm2m: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-valueattribute.Relationship columns only affect the HTML table and the
m2mextra: they do not change the columns returned for each row.?_nocol=COLUMN1&_nocol=COLUMN2List 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/offExpand foreign key references for every possible column. See below.
?_label=COLUMN1&_label=COLUMN2Expand foreign key references for one or more specified columns.
?_size=1000or?_size=maxSets a custom page size. This cannot exceed the
max_returned_rowslimit passed todatasette serve. Usemaxto getmax_returned_rows.?_sort=COLUMNSorts the results by the specified column.
?_sort_desc=COLUMNSorts the results by the specified column in descending order.
?_search=keywordsFor SQLite tables that have been configured for full-text search executes a search with the provided keywords.
?_search_COLUMN=keywordsLike
_search=but allows you to specify the column to be searched, as opposed to searching all columns that have been indexed by FTS.?_searchmode=rawWith 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-fragmentIf 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=valueFilter rows by a many-to-many relationship through another table, known as a junction table.
TABLEmust have a foreign key to the current table and a foreign key to a third table, andvalueis a value of that second foreign key, usually the primary key of a row in the third table.For example,
roadside_attraction_characteristicshas anattraction_idforeign key toroadside_attractionsand acharacteristic_idforeign key toattraction_characteristic. To show just the attractions that have the characteristic with ID 1 ("Museum"):?_m2m.roadside_attraction_characteristics=1Here's an example.
Add a lookup to the key to change how the value is matched:
?_m2m.TABLE=valueor?_m2m.TABLE__exact=value: rows related tovalue.?_m2m.TABLE__not=value: rows not related tovalue, 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=2returns 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
followstable withfollower_idandfollowed_idcolumns), 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,__notinor__exact, such as a junction table calledtags__in, would be read as that lookup, so add__exactto filter by it:?_m2m.tags__in__exact=1, or?_m2m.tags__in__not=1for 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
400error 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=valuein its place, see the upgrade guide. This redirect will be removed in a later release.?_next=TOKENPagination by continuation token - pass the token that was returned in the
"next"property by the previous page.?_facet=columnFacet 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=100Increase the number of facet results returned for each facet. Use
?_facet_size=maxfor the maximum available size, determined by max_returned_rows.?_nofacet=1Disable all facets and facet suggestions for this page, including any defined by Facets in configuration.
?_nosuggest=1Disable facet suggestions for this page.
?_nocount=1Disable the
select count(*)query used on this page - a count ofNonewill be returned instead.?_m2m_size=NThe 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
400error.?_m2m_size=0returns just the counts.?_m2m_truncate=0Return 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
m2mextra. 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. Usenullfor 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.
m2mcan only be used when inserting exactly one row, and not with"ignore": true,"replace": trueor the upsert API.All of the relationships together can have at most 1,000
add,updateandremoveitems, the same limit as the link API. A request with more is a400error, such asA 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
idof1to set bothtitleanddescriptionto the new valuesUpdate the row with
idof2to settitleto the new value -descriptionwill be left unchangedInsert a new row with
idof3and bothtitleanddescriptionset 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.
Changing a row and its links together¶
The m2m key changes the row's many-to-many links along with its columns, in one transaction. It works like the m2m key of the insert API, with add, update and remove lists for each relationship. The row edit dialog saves a row and its links with a single request like this:
{
"update": {"title": "New title"},
"m2m": {
"movie_tags": {"add": [5, {"create": {"tag": "noir"}}], "remove": [9]},
"movie_actors": {"update": [{"value": 3, "through": {"role": "Lead"}}]}
}
}
The columns are updated first, then each relationship's links are changed, in the order given. If anything fails, nothing is changed.
updatecan be left out, or be{}, to change only links.A request cannot change both the column that a relationship links with, usually the primary key, and that relationship's links.
All of the relationships together can have at most 1,000
add,updateandremoveitems, the same limit as the link API. A request with more is a400error, such asA request can have at most 1000 add, update and remove items in all, got 1001.
The response has an m2m object with, for each relationship, what the link API returns for it.
Errors are reported as they are for the insert API: all of them together, those about a relationship starting with m2m.<name>:, such as m2m.movie_tags: Permission denied: need delete-row on movie_tags, with a 403 status if any is a permission error and 400 otherwise. A row that was deleted while the request was handled is a 404.
A request that changes columns needs update-row on the table. A request that only changes links does not: like the link API, it needs view-table on the table. Each relationship needs the same permissions as it does for the link API.
The row's update-row event is recorded if any columns changed, then the link API's events for each relationship.
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.
Deleting many-to-many links along with a row¶
delete_m2m is a list of relationship names. Every junction table row of those relationships that points at the row is deleted, along with the values of its extra columns. The relationships of a table are listed by the m2m extra and by the relationships API.
A relationship can be named if its links can be removed with the link API: its junction table is a plain junction table or a junction table with extra columns (How relationships are detected), or the relationship is listed in the m2m table configuration.
For a self-referential junction table, name both relationships, such as
related_movies.related_idandrelated_movies.movie_id, to delete the junction rows that point at the row from either column.Each relationship needs the delete-row permission on its junction table.
The counts in
m2m_deletedare junction table rows.
Errors are 400 for a value that is not a list of names, an unknown name (Not a many-to-many relationship of movies: nope. Use one of: movie_actors, ...) or a repeatable junction table that is not configured, and 403 without the permission or for an immutable database.
Each junction table row that is deleted records a delete-row event for its junction table, so a row with thousands of links records thousands of events. This may change, see issue 3141.
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.
Adding and removing many-to-many links¶
To link a row to rows in another table through a many-to-many relationship, to remove those links, or to change their extra columns, make a POST to /<database>/<table>/<row-pks>/-/m2m/<relationship>. This inserts, updates and deletes rows in the junction table.
POST /<database>/<table>/<row-pks>/-/m2m/<relationship>
Content-Type: application/json
Authorization: Bearer dstok_<rest-of-token>
{
"add": [5, {"value": 7, "through": {"role": "Lead"}}],
"update": [{"value": 3, "through": {"role": "Narrator"}}],
"remove": [9]
}
<row-pks> is the tilde-encoded primary key of the row, and <relationship> is a relationship name, such as movie_tags. The relationship does not have to be one that is shown on the table's pages, but its junction table must be a plain junction table or a junction table with extra columns (How relationships are detected), or the relationship must be listed in the m2m table configuration.
add, update and remove are all optional lists, with up to 1,000 items in all: 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. Their values are keys of rows in the related table, as strings or numbers.
removeis a list of values.addis a list of values, or of objects with avalueand athroughobject that sets the junction table's extra columns for the new link. An item can also be{"create": {"<label column>": "<label>"}}to create a row of the related table and link it.updateis a list of objects with avalueand athroughobject, which set extra columns of links that already exist.
through can only name extra columns. Its values are strings, numbers or null, or binary values as {"$base64": true, "encoded": "..."}.
Removals are applied first, then updates, then additions, in a single write transaction: if any part fails, nothing is written.
Removing a value deletes every link between the two rows. Removing a value that is not linked does nothing.
Updating a value that is not linked is an error.
updatecannot be used if the junction table can link the same pair of rows more than once.Adding a value that is already linked does nothing: use
updateto change its extra columns. If the junction table can link the same pair of rows more than once, a link is only skipped if one exists with the same values for the extra columns given inthrough: adding a secondrolefor an actor adds a link, and adding the sameroleagain does not. Each added value must exist in the related table. Extra columns left out ofthroughget their default value, ornull, and aNOT NULLextra column with no default must be given a value.
If successful, this returns a 200 status code with the number of links added, removed and updated, the related rows that were created, and the row's related rows after the change, in the same format as a value in the rows of the m2m extra. Up to 20 related rows are returned: add ?_m2m_size=N to the URL for a different number, up to 100.
For example, adding tags 3 and 5 to a movie with no tags:
POST /m2m/movies/1/-/m2m/movie_tags
{
"add": [3, 5]
}
Returns:
{
"ok": true,
"added": 2,
"removed": 0,
"updated": 0,
"created": [],
"name": "movie_tags",
"row_path": "1",
"can_add": true,
"can_remove": true,
"can_update": true,
"can_create": true,
"timed_out": false,
"total": 2,
"total_capped": false,
"truncated": false,
"items": [
{
"value": 5,
"label": "time-travel",
"url": "/m2m/tags/5",
"links": [
{
"path": "1,5",
"url": "/m2m/movie_tags/1,5"
}
]
},
{
"value": 3,
"label": "heist",
"url": "/m2m/tags/3",
"links": [
{
"path": "1,3",
"url": "/m2m/movie_tags/1,3"
}
]
}
],
"url": "/m2m/tags?_m2m.movie_tags=1"
}
Any errors will use the standard error format, and nothing is written:
400for a body that is not in the format described above, athroughcolumn that is not an extra column, a value to add that is not in the related table (Values not found in tags.id: 99), a required extra column with no value, an update of a value that is not linked, or a change that SQLite rejects.400for a repeatable junction table whose relationship is not configured.403without the permission the change needs, such asPermission denied: need update-row on movie_tags, or for an immutable database.404if the database, table, row or relationship does not exist, or the actor cannot see it.
Adding links requires the insert-row permission on the junction table, removing them requires delete-row on the junction table, and updating them requires update-row on the junction table. The actor also needs view-table on the table, the junction table and the related table.
Adding links records an insert-rows event for the junction table, each updated link an update-row event, and each junction table row that is removed a delete-row event. Removing a large number of links records an event for each, which may change, see issue 3141.
To change links along with a row's columns, or to insert a row with its links, in one transaction, use the m2m key of the row update or row insert API instead.
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.
linksis the number of rows in the junction table, counted up to 10,000.links_cappedistrueif there are more than that. If counting takes longer than facet_time_limit_ms,linksisnullandlinks_timed_outistrue.extra_columnslists the names of the junction table's extra columns.displayedisfalsefor 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_configis"list"for a table with a list like that,"off"form2m: falseandnullotherwise.can_removeistrueif the actor can remove the relationship with thedrop_m2moperation 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_kindisplain,extra_columnsorrepeatable; a repeatable junction table cannot be removed this way.can_createistrueif the actor can create relationships with theadd_m2moperation 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: a404means there is no table or view with that name. A table the actor cannot view gives a403, and indexes and triggers are not tables, so a client that leavesnameout of theadd_m2moperation 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:
tableis the name of the table to create. This field is required.columnsis a list of columns to create. Each column is a dictionary withnameandtypekeys.nameis the name of the column. This is required.typeis the type of the column. This is optional - if not provided,textwill be assumed. The valid types aretext,integer,floatandblob.not_nullcan be set totrueto create this column with aNOT NULLconstraint.defaultcan be used to set a literal default value for this column.default_exprcan be used instead ofdefaultto set a SQLite default expression. See default_expr values.fk_tablecan be used to create a single-column foreign key constraint referencing another table.fk_columnis optional and can be used to specify the referenced column - if omitted, Datasette will use the single primary key offk_table. Datasette creates an index on each foreign key column, namedidx_<table>_<column>, unless the column is the table's primary key or already starts an index.
pkis the primary key for the table. This is optional - if not provided, Datasette will create a SQLite table with a hiddenrowidcolumn.If the primary key is an integer column, it will be configured to automatically increment for each new record.
If you set this to
idwithout including anidcolumn in the list ofcolumns, Datasette will create an auto-incrementing integer ID column for you.pkscan be used instead ofpkto 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 examplerows.ignorecan be set totrueto ignore existing rows by primary key if the table already exists.replacecan be set totrueto replace existing rows by primary key if the table already exists. This requires the update-row permission.altercan be set totrueif you want to automatically add any missing columns to the table. This requires the alter-table permission.m2mcan 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 theargsof anadd_m2moperation of the alter table API, such as{"other_table": "tags"}or{"new_table": {"table": "authors"}}. An item can name the new table itself as itsother_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 examplem2m.1: Table not found: nope. The response then hascreated_tablesandm2mkeys, as described for the alter table API, with the new table first increated_tables. Creating relationships needs the same permissions as there.m2mcannot be used if the table already exists.
default_expr accepts these values:
Value |
Recommended column type |
Example inserted value |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_columnadds a new column.argsacceptsname, optionaltypeoftext,integer,floatorblob, optionalnot_null, optional literaldefaultand optionaldefault_expr. Ifnot_nullistrueeither a non-nulldefaultordefault_expris required.rename_columnrenames a column.argsacceptsnameandto.rename_tablerenames the table.argsacceptsto, 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_columnchanges column properties.argsacceptsnameand at least one oftype,not_null, literaldefaultordefault_expr. Passing"default": nullremoves an existing default.drop_columndrops a column.argsacceptsname.set_primary_keychanges the table primary key.argsacceptscolumns, a list of one or more column names.add_foreign_keyadds a single-column foreign key constraint.argsacceptscolumn,fk_tableand optionalfk_column. Iffk_columnis omitted, Datasette will use the single primary key offk_table.drop_foreign_keyremoves the foreign key constraint for a column.argsacceptscolumn.set_foreign_keysreplaces all foreign key constraints on the table.argsacceptsforeign_keys, a list of objects that each havecolumn,fk_tableand optionalfk_column. An empty list removes all foreign key constraints.Each new foreign key that
add_foreign_keyorset_foreign_keysadds gets an index on its column namedidx_<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 ifset_foreign_keyslists them again. Removing a foreign key constraint keeps the column, and any index on it.reorder_columnsreorders columns.argsacceptscolumns, a list of one or more column names. Columns omitted from this list will appear afterwards in their existing order.add_m2mcreates a many-to-many relationship between this table and another table, by creating a junction table.argsacceptsother_tableornew_table, and an optional junction tablename. See Adding and removing relationships while altering a table.drop_m2mremoves a many-to-many relationship by dropping its junction table.argsacceptsjunction, 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_columnwith a default as described above, fails with an error such aserror in view movies_view: no such table: main.moviesand nothing is changed. Changes made in place, such as anadd_columnwithout a default, still work.Before SQLite 3.26.0
rename_tableonly updates the foreign keys in other tables that reference the table ifPRAGMA foreign_keysis 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_tableis 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_tablecreates the other table at the same time, for example{"table": "awards", "label_column": "name"}. The new table has anidinteger primary key and a text column namedlabel_column, which defaults tonameand 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 asmovies_tags, with_2,_3and so on added if that name is taken by any table, view, index or trigger. Anamethat 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_tablesanddropped_tableslist the tables that were created and dropped. Anew_tableis listed before its junction table.m2mdescribes the new relationships, keyed by relationship name, in the format of therelationshipsof the relationships API. A self-referential junction table has two relationships, one in each direction.m2m_configis"list"or"off"if the table's m2m table configuration lists its relationships or turns them off, andnullotherwise. New relationships are then not shown on the table's pages until they are added to that list, and theirdisplayedisfalse.m2m_droppedhas thejunction,row_count(the number of rows deleted) andrelationships(the names of the relationships removed, two for a self-referential junction table) of each junction table that was dropped.alteredisfalseif 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:
400forargsthat are not in the format described above, a table that is a view or does not have a single-column primary key, a junctionnameornew_tablethat exists already, adrop_m2mtable that is not a junction table of this table or is a repeatable junction table, or more than 20add_m2moperations. An error for a name that is taken says what has it, such asa table named movies_tags already exists.403for a missing permission, or if the database is immutable.404if 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.