Working with data through the HTTP interface
In this section, you will learn how to create a table, add data to it, and then read it using the Document API HTTP interface.
For HTTP queries, the examples in the section use the cURL
Warning
You can only access document tables using the Document API.
Getting started
-
If you do not have the Yandex Cloud command line interface yet, install and initialize it.
-
Prepare the Document API endpoint of the created database.
How do I find out the Document API endpoint of a database?
-
Go to the management console
. -
Select the folder and go to Managed Service for YDB.
-
Select the database you want to query.
-
In the menu on the left, go to the Overview section.
-
The endpoint value is in the Document API endpoint line.
Example of an
https://docapi.serverless.yandexcloud.net/ru-central1/b1gia87mbaomkfvs6rgl/etnudu2n9ri35luqe4h1
endpoint value.
Note
For the Amazon DynamoDB-compatible mode, use a serverless database configuration.
-
-
Set the
ENDPOINT
environment variable to the prepared value:export ENDPOINT=<Document_API_endpoint>
Creating a table
Set the table configuration in the create.json
file:
{
"TableName": "test/pets",
"AttributeDefinitions":
[
{
"AttributeName": "species",
"AttributeType": "S"
},
{
"AttributeName": "name",
"AttributeType": "S"
}
],
"KeySchema":
[
{
"AttributeName": "species",
"KeyType": "HASH"
},
{
"AttributeName": "name",
"KeyType": "RANGE"
}
]
}
Create a document table in the database using the command:
curl \
--header 'X-Amz-Target: DynamoDB_20120810.CreateTable' \
--header "Authorization: Bearer $(yc iam create-token)" \
--header "Content-Type: application.json" \
--data @create.json $ENDPOINT
For more information about the CreateTable
method, see the Document API reference.
Adding data
Prepare data to save to the document table by creating a file named put.json
:
{
"TableName": "test/pets",
"Item":
{
"species": {"S": "cat"},
"name": {"S": "Tom"},
"color": {"S": "black"},
"price": {"N": "10.5"}
}
}
Add the data to the table using the command:
curl \
--header 'X-Amz-Target: DynamoDB_20120810.PutItem' \
--header "Authorization: Bearer $(yc iam create-token)" \
--header "Content-Type: application.json" \
--data @put.json $ENDPOINT
For more information about the PutItem
method, see the Document API reference.
Reading a record
To read the data from the document table, run the command:
curl \
--header 'X-Amz-Target: DynamoDB_20120810.GetItem' \
--header "Authorization: Bearer $(yc iam create-token)" \
--header "Content-Type: application.json" \
--data '{"TableName": "test/pets", "Key": {"species":{"S":"cat"}, "name":{"S":"Tom"}}}' \
$ENDPOINT
Result:
{"Item":{"name":{"S":"Tom"},"species":{"S":"cat"},"color":{"S":"black"},"price":{"N":"10.5"}}}
For more information about the GetItem
method, see the Document API reference.