API

What is the SQL API?

DoltHub provides an API for accessing Dolt databases via web requests. A Dolt database can be attached to a DoltHub remote and pushed. At that point DoltHub provides an API against which users can execute Dolt SQL with results returned as JSON.

Example

Reading

We will use an example DoltHub database, dolthub/ip-to-country and the Python requests library to explore it in the Python console:
1
import requests
2
owner, repo = 'dolthub', 'ip-to-country'
3
res = requests.get('https://dolthub.com/api/v1alpha1/{}/{}'.format(owner, repo))
4
res.json()
Copied!
This shows our repository metadata as a dictionary:
1
{'query_execution_status': 'Success',
2
'query_execution_message': '',
3
'repository_owner': 'dolthub',
4
'repository_name': 'ip-to-country',
5
'commit_ref': 'master',
6
'sql_query': 'SHOW TABLES;',
7
'schema': [{'columnName': 'Table',
8
'columnType': 'String',
9
'isPrimaryKey': False}],
10
'rows': [{'Table': 'IPv4ToCountry'}, {'Table': 'IPv6ToCountry'}]}
Copied!
We can now execute a query:
1
query = '''SELECT * FROM IPv4ToCountry WHERE CountryCode2Letter = "AU"'''
2
res = requests.get('https://www.dolthub.com/api/v1alpha1/{}/{}/{}'.format(owner, repo, branch), params={'q': query})
3
res.json()
Copied!
This yields the results as JSON, with both schema and data:
1
{'query_execution_status': 'RowLimit',
2
'query_execution_message': '',
3
'repository_owner': 'dolthub',
4
'repository_name': 'ip-to-country',
5
'commit_ref': 'master',
6
'sql_query': 'SELECT * FROM IPv4ToCountry WHERE CountryCode2Letter = "AU"',
7
'schema': [{'columnName': 'IPFrom',
8
'columnType': 'Int',
9
'isPrimaryKey': False},
10
{'columnName': 'IpTo', 'columnType': 'Int', 'isPrimaryKey': False},
11
{'columnName': 'Registry', 'columnType': 'String', 'isPrimaryKey': False},
12
{'columnName': 'AssignedDate', 'columnType': 'Int', 'isPrimaryKey': False},
13
{'columnName': 'CountryCode2Letter',
14
'columnType': 'String',
15
'isPrimaryKey': False},
16
{'columnName': 'CountryCode3Letter',
17
'columnType': 'String',
18
'isPrimaryKey': False},
19
{'columnName': 'Country', 'columnType': 'String', 'isPrimaryKey': False}],
20
'rows': [{'IPFrom': '16777216',
21
'IpTo': '16777471',
22
'Registry': 'apnic',
23
'AssignedDate': '1313020800',
24
'CountryCode2Letter': 'AU',
25
'CountryCode3Letter': 'AUS',
26
'Country': 'Australia'},
27
.
28
.
29
.
Copied!
As a reminder, this API is in Alpha version, and we will continue to flesh this out, as well as improve query performance, over time.
You can also explore our SQL API on DoltHub whenever you execute a query:
SQL API Tab

Writing

Since adding, updating, and deleting data can take a bit of time to execute against larger databases, we made the writable API asynchronous. Therefore we needed to add two new HTTP endpoints for executing these kinds of queries using the SQL API.
We can use our SHAQ database as an example. Let's say we want to update a player's id in the player stats table.
First, we want to hit the write endpoint with our UPDATE query. This will start an asynchronous operation.
1
owner, repo, from_branch, to_branch = 'dolthub', 'SHAQ', 'main', 'update-player'
2
query = '''UPDATE player_season_stat_totals SET player_id=714287 WHERE player_id=15404617'''
3
headers = {
4
'authorization': 'token [see Authentication section below for token]'
5
}
6
write_res = requests.post(
7
f'https://www.dolthub.com/api/v1alpha1/{owner}/{repo}/write/{from_branch}/{to_branch}',
8
params={'q': query},
9
headers=headers,
10
)
11
write_json = write_res.json()
Copied!
The main branch already exists in the database, and providing a <to_branch> that doesn't exist will create this new branch from the <from_branch>.
The yielded JSON results include an operation_name.
1
{
2
"query_execution_status": "Success",
3
"query_execution_message": "",
4
"repository_owner": "dolthub",
5
"repository_name": "SHAQ",
6
"to_branch_name": "update-player",
7
"from_branch_name": "main",
8
"query": "UPDATE player_season_stat_totals SET player_id=714287 WHERE player_id=15404617",
9
"operation_name": "operations/72abb56b-d478-43ae-9a2d-c9602184c7ab"
10
}
Copied!
operation_name can be used to poll the second endpoint to check if the operation is done.
1
def get_operation(op_name):
2
op_res = requests.get(
3
f'https://www.dolthub.com/api/v1alpha1/{owner}/{repo}/write',
4
params={'operationName': op_name},
5
headers=headers,
6
)
7
return op_res.json()
8
9
10
def poll_operation(op_name):
11
done = False
12
while done == False:
13
poll_res = get_operation(op_name)
14
done = poll_res['done']
15
if done:
16
return poll_res
17
else:
18
time.sleep(3)
19
20
21
res = poll_operation(write_json['operation_name'])
Copied!
A done operation will yield a response that includes some query metadata, including from and to commit ids.
1
{
2
"_id": "operations/72abb56b-d478-43ae-9a2d-c9602184c7ab",
3
"done": true,
4
"res_details": {
5
"query_execution_status": "Success",
6
"query_execution_message": "Query OK, 2 rows affected. Rows matched: 2 Changed: 2 Warnings: 0.",
7
"owner_name": "tbantle",
8
"repository_name": "SHAQ",
9
"from_commit_id": "518ue176ec13qf563e87uoerkqqepood",
10
"to_commit_id": "5sp7i0bov6itma2u04dpk15ui24lrigp"
11
}
12
}
Copied!
Since a lot of Dolt's functionality is exposed via SQL, we can use the commit ids to query the dolt_commit_diff_$tablename table to view the resulting diff from our UPDATE query.
1
from_commit, to_commit = res['res_details']['from_commit_id'], res['res_details']['to_commit_id']
2
query = f'''SELECT from_player_id, to_player_id, diff_type FROM `dolt_commit_diff_player_season_stat_totals` WHERE from_commit="{from_commit}" AND to_commit="{to_commit}"'''
3
diff_res = requests.get(
4
f'https://www.dolthub.com/api/v1alpha1/{owner}/{repo}/{to_branch}',
5
params={'q': query},
6
headers=headers,
7
)
8
diff_res.json()
Copied!
We can repeat this process with as many queries as we want. Every query will create a commit on the <from_branch>.
Once we're satisfied with our changes, we can merge our branches by hitting the first endpoint with an empty query.
1
merge_res = requests.post(
2
f'https://www.dolthub.com/api/v1alpha1/{owner}/{repo}/write/{to_branch}/{from_branch}',
3
params=None,
4
headers=headers,
5
)
6
7
merge_json = merge_res.json()
8
pollOperation(merge_json['operation_name'])
Copied!
You can learn more about using the writable SQL API here.

Authentication

API tokens can be used to authenticate calls to the SQL API over Basic Authentication. This is useful for executing SQL queries against private databases or executing write queries.
First, create an API token in your settings on DoltHub. Copy the token right away, as you won't be able to see it again.
Token settings
Now you can use this token in the header when executing a query against a private database.
1
owner, repo, branch = "dolthub", "private-db", "main"
2
query = """SELECT * FROM testtable"""
3
4
res = requests.get(
5
"https://www.dolthub.com/api/v1alpha1/{}/{}".format(owner, repo, branch),
6
params={"q": query},
7
headers={ "authorization": "token [TOKEN YOU COPIED]" },
8
)
9
10
res.json()
Copied!
Please note: You must include a ref name (branch, tag, commit hash, etc) when making authenticated calls to the SQL API using a token. Unauthenticated API requests do not require this. They use the default branch (main or master).
Export as PDF
Copy link
Edit on GitHub