Debian Codegraph @

docs/json_api.rst

raw
1 .. _json_api:
2
3 JSON API
4 ========
5
6 Datasette provides a JSON API for your SQLite databases. Anything you can do
7 through the Datasette user interface can also be accessed as JSON via the API.
8
9 To access the API for a page, either click on the ``.json`` link on that page or
10 edit the URL and add a ``.json`` extension to it.
11
12 If you started Datasette with the ``--cors`` option, each JSON endpoint will be
13 served with the following additional HTTP headers::
14
15 Access-Control-Allow-Origin: *
16 Access-Control-Allow-Headers: Authorization
17 Access-Control-Expose-Headers: Link
18
19 This means JavaScript running on any domain will be able to make cross-origin
20 requests to fetch the data.
21
22 If you start Datasette without the ``--cors`` option only JavaScript running on
23 the same domain as Datasette will be able to access the API.
24
25 .. _json_api_shapes:
26
27 Different shapes
28 ----------------
29
30 The default JSON representation of data from a SQLite table or custom query
31 looks like this::
32
33 {
34 "database": "sf-trees",
35 "table": "qSpecies",
36 "columns": [
37 "id",
38 "value"
39 ],
40 "rows": [
41 [
42 1,
43 "Myoporum laetum :: Myoporum"
44 ],
45 [
46 2,
47 "Metrosideros excelsa :: New Zealand Xmas Tree"
48 ],
49 [
50 3,
51 "Pinus radiata :: Monterey Pine"
52 ]
53 ],
54 "truncated": false,
55 "next": "100",
56 "next_url": "http://127.0.0.1:8001/sf-trees-02c8ef1/qSpecies.json?_next=100",
57 "query_ms": 1.9571781158447266
58 }
59
60 The ``columns`` key lists the columns that are being returned, and the ``rows``
61 key then returns a list of lists, each one representing a row. The order of the
62 values in each row corresponds to the columns.
63
64 The ``_shape`` parameter can be used to access alternative formats for the
65 ``rows`` key which may be more convenient for your application. There are three
66 options:
67
68 * ``?_shape=arrays`` - ``"rows"`` is the default option, shown above
69 * ``?_shape=objects`` - ``"rows"`` is a list of JSON key/value objects
70 * ``?_shape=array`` - an JSON array of objects
71 * ``?_shape=array&_nl=on`` - a newline-separated list of JSON objects
72 * ``?_shape=arrayfirst`` - a flat JSON array containing just the first value from each row
73 * ``?_shape=object`` - a JSON object keyed using the primary keys of the rows
74
75 ``_shape=objects`` looks like this::
76
77 {
78 "database": "sf-trees",
79 ...
80 "rows": [
81 {
82 "id": 1,
83 "value": "Myoporum laetum :: Myoporum"
84 },
85 {
86 "id": 2,
87 "value": "Metrosideros excelsa :: New Zealand Xmas Tree"
88 },
89 {
90 "id": 3,
91 "value": "Pinus radiata :: Monterey Pine"
92 }
93 ]
94 }
95
96 ``_shape=array`` looks like this::
97
98 [
99 {
100 "id": 1,
101 "value": "Myoporum laetum :: Myoporum"
102 },
103 {
104 "id": 2,
105 "value": "Metrosideros excelsa :: New Zealand Xmas Tree"
106 },
107 {
108 "id": 3,
109 "value": "Pinus radiata :: Monterey Pine"
110 }
111 ]
112
113 ``_shape=array&_nl=on`` looks like this::
114
115 {"id": 1, "value": "Myoporum laetum :: Myoporum"}
116 {"id": 2, "value": "Metrosideros excelsa :: New Zealand Xmas Tree"}
117 {"id": 3, "value": "Pinus radiata :: Monterey Pine"}
118
119 ``_shape=arrayfirst`` looks like this::
120
121 [1, 2, 3]
122
123 ``_shape=object`` looks like this::
124
125 {
126 "1": {
127 "id": 1,
128 "value": "Myoporum laetum :: Myoporum"
129 },
130 "2": {
131 "id": 2,
132 "value": "Metrosideros excelsa :: New Zealand Xmas Tree"
133 },
134 "3": {
135 "id": 3,
136 "value": "Pinus radiata :: Monterey Pine"
137 }
138 ]
139
140 The ``object`` shape is only available for queries against tables - custom SQL
141 queries and views do not have an obvious primary key so cannot be returned using
142 this format.
143
144 The ``object`` keys are always strings. If your table has a compound primary
145 key, the ``object`` keys will be a comma-separated string.
146
147 .. _json_api_pagination:
148
149 Pagination
150 ----------
151
152 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.
153
154 Other representations include pagination information in the ``link`` HTTP header. That header will look something like this::
155
156 link: <https://latest.datasette.io/fixtures/sortable.json?_next=d%2Cv>; rel="next"
157
158 Here is an example Python function built using `requests <https://requests.readthedocs.io/>`__ that returns a list of all of the paginated items from one of these API endpoints:
159
160 .. code-block:: python
161
162 def paginate(url):
163 items = []
164 while url:
165 response = requests.get(url)
166 try:
167 url = response.links.get("next").get("url")
168 except AttributeError:
169 url = None
170 items.extend(response.json())
171 return items
172
173 .. _json_api_special:
174
175 Special JSON arguments
176 ----------------------
177
178 Every Datasette endpoint that can return JSON also accepts the following
179 query string arguments:
180
181 ``?_shape=SHAPE``
182 The shape of the JSON to return, documented above.
183
184 ``?_nl=on``
185 When used with ``?_shape=array`` produces newline-delimited JSON objects.
186
187 ``?_json=COLUMN1&_json=COLUMN2``
188 If any of your SQLite columns contain JSON values, you can use one or more
189 ``_json=`` parameters to request that those columns be returned as regular
190 JSON. Without this argument those columns will be returned as JSON objects
191 that have been double-encoded into a JSON string value.
192
193 Compare `this query without the argument <https://fivethirtyeight.datasettes.com/fivethirtyeight.json?sql=select+%27{%22this+is%22%3A+%22a+json+object%22}%27+as+d&_shape=array>`_ to `this query using the argument <https://fivethirtyeight.datasettes.com/fivethirtyeight.json?sql=select+%27{%22this+is%22%3A+%22a+json+object%22}%27+as+d&_shape=array&_json=d>`_
194
195 ``?_json_infinity=on``
196 If your data contains infinity or -infinity values, Datasette will replace
197 them with None when returning them as JSON. If you pass ``_json_infinity=1``
198 Datasette will instead return them as ``Infinity`` or ``-Infinity`` which is
199 invalid JSON but can be processed by some custom JSON parsers.
200
201 ``?_timelimit=MS``
202 Sets a custom time limit for the query in ms. You can use this for optimistic
203 queries where you would like Datasette to give up if the query takes too
204 long, for example if you want to implement autocomplete search but only if
205 it can be executed in less than 10ms.
206
207 ``?_ttl=SECONDS``
208 For how many seconds should this response be cached by HTTP proxies? Use
209 ``?_ttl=0`` to disable HTTP caching entirely for this request.
210
211 ``?_trace=1``
212 Turns on tracing for this page: SQL queries executed during the request will
213 be gathered and included in the response, either in a new ``"_traces"`` key
214 for JSON responses or at the bottom of the page if the response is in HTML.
215
216 The structure of the data returned here should be considered highly unstable
217 and very likely to change.
218
219 Only available if the :ref:`setting_trace_debug` setting is enabled.
220
221 .. _table_arguments:
222
223 Table arguments
224 ---------------
225
226 The Datasette table view takes a number of special query string arguments.
227
228 Column filter arguments
229 ~~~~~~~~~~~~~~~~~~~~~~~
230
231 You can filter the data returned by the table based on column values using a query string argument.
232
233 ``?column__exact=value`` or ``?_column=value``
234 Returns rows where the specified column exactly matches the value.
235
236 ``?column__not=value``
237 Returns rows where the column does not match the value.
238
239 ``?column__contains=value``
240 Rows where the string column contains the specified value (``column like "%value%"`` in SQL).
241
242 ``?column__endswith=value``
243 Rows where the string column ends with the specified value (``column like "%value"`` in SQL).
244
245 ``?column__startswith=value``
246 Rows where the string column starts with the specified value (``column like "value%"`` in SQL).
247
248 ``?column__gt=value``
249 Rows which are greater than the specified value.
250
251 ``?column__gte=value``
252 Rows which are greater than or equal to the specified value.
253
254 ``?column__lt=value``
255 Rows which are less than the specified value.
256
257 ``?column__lte=value``
258 Rows which are less than or equal to the specified value.
259
260 ``?column__like=value``
261 Match rows with a LIKE clause, case insensitive and with ``%`` as the wildcard character.
262
263 ``?column__notlike=value``
264 Match rows that do not match the provided LIKE clause.
265
266 ``?column__glob=value``
267 Similar to LIKE but uses Unix wildcard syntax and is case sensitive.
268
269 ``?column__in=value1,value2,value3``
270 Rows where column matches any of the provided values.
271
272 You can use a comma separated string, or you can use a JSON array.
273
274 The JSON array option is useful if one of your matching values itself contains a comma:
275
276 ``?column__in=["value","value,with,commas"]``
277
278 ``?column__notin=value1,value2,value3``
279 Rows where column does not match any of the provided values. The inverse of ``__in=``. Also supports JSON arrays.
280
281 ``?column__arraycontains=value``
282 Works against columns that contain JSON arrays - matches if any of the values in that array match the provided value.
283
284 This is only available if the ``json1`` SQLite extension is enabled.
285
286 ``?column__arraynotcontains=value``
287 Works against columns that contain JSON arrays - matches if none of the values in that array match the provided value.
288
289 This is only available if the ``json1`` SQLite extension is enabled.
290
291 ``?column__date=value``
292 Column is a datestamp occurring on the specified YYYY-MM-DD date, e.g. ``2018-01-02``.
293
294 ``?column__isnull=1``
295 Matches rows where the column is null.
296
297 ``?column__notnull=1``
298 Matches rows where the column is not null.
299
300 ``?column__isblank=1``
301 Matches rows where the column is blank, meaning null or the empty string.
302
303 ``?column__notblank=1``
304 Matches rows where the column is not blank.
305
306 .. _json_api_table_arguments:
307
308 Special table arguments
309 ~~~~~~~~~~~~~~~~~~~~~~~
310
311 ``?_col=COLUMN1&_col=COLUMN2``
312 List specific columns to display. These will be shown along with any primary keys.
313
314 ``?_nocol=COLUMN1&_nocol=COLUMN2``
315 List specific columns to hide - any column not listed will be displayed. Primary keys cannot be hidden.
316
317 ``?_labels=on/off``
318 Expand foreign key references for every possible column. See below.
319
320 ``?_label=COLUMN1&_label=COLUMN2``
321 Expand foreign key references for one or more specified columns.
322
323 ``?_size=1000`` or ``?_size=max``
324 Sets a custom page size. This cannot exceed the ``max_returned_rows`` limit
325 passed to ``datasette serve``. Use ``max`` to get ``max_returned_rows``.
326
327 ``?_sort=COLUMN``
328 Sorts the results by the specified column.
329
330 ``?_sort_desc=COLUMN``
331 Sorts the results by the specified column in descending order.
332
333 ``?_search=keywords``
334 For SQLite tables that have been configured for
335 `full-text search <https://www.sqlite.org/fts3.html>`_ executes a search
336 with the provided keywords.
337
338 ``?_search_COLUMN=keywords``
339 Like ``_search=`` but allows you to specify the column to be searched, as
340 opposed to searching all columns that have been indexed by FTS.
341
342 ``?_searchmode=raw``
343 With this option, queries passed to ``?_search=`` or ``?_search_COLUMN=`` will
344 not have special characters escaped. This means you can make use of the full
345 set of `advanced SQLite FTS syntax <https://www.sqlite.org/fts5.html#full_text_query_syntax>`__,
346 though this could potentially result in errors if the wrong syntax is used.
347
348 ``?_where=SQL-fragment``
349 If the :ref:`permissions_execute_sql` permission is enabled, this parameter
350 can be used to pass one or more additional SQL fragments to be used in the
351 `WHERE` clause of the SQL used to query the table.
352
353 This is particularly useful if you are building a JavaScript application
354 that needs to do something creative but still wants the other conveniences
355 provided by the table view (such as faceting) and hence would like not to
356 have to construct a completely custom SQL query.
357
358 Some examples:
359
360 * `facetable?_where=_neighborhood like "%c%"&_where=_city_id=3 <https://latest.datasette.io/fixtures/facetable?_where=_neighborhood%20like%20%22%c%%22&_where=_city_id=3>`__
361 * `facetable?_where=_city_id in (select id from facet_cities where name != "Detroit") <https://latest.datasette.io/fixtures/facetable?_where=_city_id%20in%20(select%20id%20from%20facet_cities%20where%20name%20!=%20%22Detroit%22)>`__
362
363 ``?_through={json}``
364 This can be used to filter rows via a join against another table.
365
366 The JSON parameter must include three keys: ``table``, ``column`` and ``value``.
367
368 ``table`` must be a table that the current table is related to via a foreign key relationship.
369
370 ``column`` must be a column in that other table.
371
372 ``value`` is the value that you want to match against.
373
374 For example, to filter ``roadside_attractions`` to just show the attractions that have a characteristic of "museum", you would construct this JSON::
375
376 {
377 "table": "roadside_attraction_characteristics",
378 "column": "characteristic_id",
379 "value": "1"
380 }
381
382 As a URL, that looks like this:
383
384 ``?_through={%22table%22:%22roadside_attraction_characteristics%22,%22column%22:%22characteristic_id%22,%22value%22:%221%22}``
385
386 Here's `an example <https://latest.datasette.io/fixtures/roadside_attractions?_through={%22table%22:%22roadside_attraction_characteristics%22,%22column%22:%22characteristic_id%22,%22value%22:%221%22}>`__.
387
388 ``?_next=TOKEN``
389 Pagination by continuation token - pass the token that was returned in the
390 ``"next"`` property by the previous page.
391
392 ``?_facet=column``
393 Facet by column. Can be applied multiple times, see :ref:`facets`. Only works on the default JSON output, not on any of the custom shapes.
394
395 ``?_facet_size=100``
396 Increase the number of facet results returned for each facet. Use ``?_facet_size=max`` for the maximum available size, determined by :ref:`setting_max_returned_rows`.
397
398 ``?_nofacet=1``
399 Disable all facets and facet suggestions for this page, including any defined by :ref:`facets_metadata`.
400
401 ``?_nosuggest=1``
402 Disable facet suggestions for this page.
403
404 ``?_nocount=1``
405 Disable the ``select count(*)`` query used on this page - a count of ``None`` will be returned instead.
406
407 .. _expand_foreign_keys:
408
409 Expanding foreign key references
410 --------------------------------
411
412 Datasette can detect foreign key relationships and resolve those references into
413 labels. The HTML interface does this by default for every detected foreign key
414 column - you can turn that off using ``?_labels=off``.
415
416 You can request foreign keys be expanded in JSON using the ``_labels=on`` or
417 ``_label=COLUMN`` special query string parameters. Here's what an expanded row
418 looks like::
419
420 [
421 {
422 "rowid": 1,
423 "TreeID": 141565,
424 "qLegalStatus": {
425 "value": 1,
426 "label": "Permitted Site"
427 },
428 "qSpecies": {
429 "value": 1,
430 "label": "Myoporum laetum :: Myoporum"
431 },
432 "qAddress": "501X Baker St",
433 "SiteOrder": 1
434 }
435 ]
436
437 The column in the foreign key table that is used for the label can be specified
438 in ``metadata.json`` - see :ref:`label_columns`.
439
440 .. _json_api_discover_alternate:
441
442 Discovering the JSON for a page
443 -------------------------------
444
445 Most of the HTML pages served by Datasette provide a mechanism for discovering their JSON equivalents using the HTML ``link`` mechanism.
446
447 You can find this near the top of the source code of those pages, looking like this:
448
449 .. code-block:: html
450
451 <link rel="alternate"
452 type="application/json+datasette"
453 href="https://latest.datasette.io/fixtures/sortable.json">
454
455 The JSON URL is also made available in a ``Link`` HTTP header for the page::
456
457 Link: https://latest.datasette.io/fixtures/sortable.json; rel="alternate"; type="application/json+datasette"