Deta Base SDK
The Deta library is the easiest way to store and retrieve data from your Deta Base. Currently we support JavaScript (Node + Browser), Python 3 and Go. Drop us a line if you want us to support your favorite language.
note
A "Deta Base" instance is a collection of data not unlike a Key-Value store, a MongoDB collection or a PostgreSQL/MySQL table. It will grow with your app's needs.
note
If your database keys have special characters (like &
,/
, @
etc) that are url-reserved or url-unsafe, please use the latest sdk versions to prevent unexpected behavior.
#
Installing the Deta LibraryFirst, install the Deta library in your project's directory.
- JavaScript
- Python
- Go
Using Yarn:
#
InstantiatingTo start working with your Base, you need to import the Deta
class and initialize it with a Project Key. Then instantiate a subclass called Base
with a database name of your choosing.
Deta Bases are created for you automatically when you start using them.
- JavaScript
- Python
- Go
note
If you are using Deta Base within a Deta Micro, the Deta SDK comes pre-installed and a valid project key is pre-set in the Micro's environment. There is no need to install the SDK or pass a key in the initialization step.
note
If you are using the deta
npm package of 0.0.6
or below, Deta
is the sinlge default export and should be imported as such.
note
If you are using Deta Base within a Deta Micro, the Deta SDK comes pre-installed and a valid project key is pre-set in the Micro's environment. There is no need to install the SDK or pass a key in the the initialization step.
warning
Your project key is confidential and meant to be used by you. Anyone who has your project key can access your database. Please, do not share it or commit it in your code.
#
UsingDeta's Base
class offers the following methods to interact with your Deta Base:
put
– Stores an item in the database. It will update an item if the key already exists.
insert
– Stores an item in the database but raises an error if the key already exists. (2x slower than put
).
get
– Retrieves an item from the database by its key.
fetch
– Retrieves multiple items from the database based on the provided (optional) filters.
delete
– Deletes an item from the database.
update
– Updates an item in the database.
#
Putput
is the fastest way to store an item in the database.
In the case you do not provide us with a key, we will auto generate a 12 char long string as a key.
You can also use put
when you want to update an item in the database.
- JavaScript
- Python
- Go
async put(data, key=null)
#
Parameters- data (required) – Accepts:
object
(serializable),string
,number
,boolean
andarray
.- Description: The data to be stored.
- key (optional) – Accepts:
string
andnull
- Description: the key (aka ID) to store the data under. Will be auto generated if not provided.
#
Code Example#
Returnsput
returns a promise which resolves to the item on a successful put, otherwise it throws an Error.
put(data: typing.Union[dict, list, str, int, float, bool], key:str = None):
#
Parameters- data (required) – Accepts:
dict
,str
,int
,float
,bool
andlist
.- Description: The data to be stored.
- key (optional) – Accepts:
str
andNone
- Description: the key (aka ID) to store the data under. Will be auto generated if not provided.
#
Code Example#
Returnsput
returns the item on a successful put, otherwise it raises an Error.
Put(item interface{}) (string, error)
#
Parameters- item : The item to be stored, should be a
struct
or amap
. If the item is astruct
provide the field keys for the data with json struct tags. The key of the item must have a json struct tag ofkey
.
#
Code Example#
ReturnsReturns the key
of the item stored and an error
. Possible error values:
ErrBadItem
: bad item, item is of unexpected typeErrBadRequest
: item caused a bad request response from the serverErrUnauthorized
: unuathorizedErrInternalServerError
: internal server error
#
Getget
retrieves an item from the database by it's key
.
- JavaScript
- Python
- Go
async get(key)
#
Parameters- key (required) – Accepts:
string
- Description: the key of which item is to be retrieved.
#
Code Example#
ReturnsIf the record is found, the promise resolves to:
If not found, the promise will resolve to null
.
get(key: str)
#
Parameter Types- key (required) – Accepts:
str
- Description: the key of which item is to be retrieved.
#
Code Example#
ReturnsIf the record is found:
If not found, the function will return None
.
Get(key string, dest interface{}) error
#
Parameters- key: the key of the item to be retrieved
- dest: the result will be stored into the value pointed by
dest
#
Code Example#
ReturnsReturns an error
. Possible error values:
ErrNotFound
: no item with such key was foundErrBadDestination
: bad destination, result could not be stored ontodest
ErrUnauthorized
: unauthorizedErrInternalServerError
: internal server error
#
Deletedelete
deletes an item form the database provided a key.
- JavaScript
- Python
- Go
async delete(key)
#
Parameters- key (required) – Accepts:
string
- Description: the key of which item is to be deleted.
#
Code Example#
ReturnsAlways returns a promise which resolves to null
, even if the key does not exist.
#
InsertThe insert
method inserts a single item into a Base, but is unique from put
in that it will raise an error of the key
already exists in the database.
insert
is roughly 2x slower than put
.
- JavaScript
- Python
- Go
async insert(data, key=null)
#
Parameters- data (required) – Accepts:
object
(serializable),string
,number
,boolean
andarray
.- Description: The data to be stored.
- key (optional) – Accepts:
string
andnull
- Description: the key (aka ID) to store the data under. Will be auto generated if not provided.
#
Code Example#
ReturnsReturns a promise which resolves to the item on a successful insert, and throws an error if the key already exists.
insert(data: typing.Union[dict, list, str, int, float, bool], key:str = None):
#
Parameters- data (required) – Accepts:
dict
,str
,int
,float
,bool
andlist
.- Description: The data to be stored.
- key (optional) – Accepts:
str
andNone
- Description: the key (aka ID) to store the data under. Will be auto generated if not provided.
#
Code Example#
ReturnsReturns the item on a successful insert, and throws an error if the key already exists.
Insert(item interface{}) (string, error)
#
Parameters- item : similar to
item
parameter toPut
#
Code Example#
ReturnsReturns the key
of the item inserted and an error
. Possible error values:
ErrConflict
: if item with providedkey
already existsErrBadItem
: bad item, if item is of unexpected typeErrBadRequest
: item caused a bad request response from the serverErrUnauthorized
: unauthorizedErrInternalServerError
: internal server error
#
Put ManyThe Put Many method puts up to 25 items into a Base at once on a single call.
- JavaScript
- Python
- Go
async putMany(items)
#
Parameters- items (required) – Accepts:
Array
of items, where each "item" can be anobject
(serializable),string
,number
,boolean
orarray
.- Description: The list of items to be stored.
#
Code Example#
ReturnsReturns a promise which resolves to the put items on a successful insert, and throws an error if you attempt to put more than 25 items.
put_many(items):
#
Parameters- items (required) – Accepts:
list
of items, where each "item" can be andict
(JSON serializable),str
,int
,bool
,float
orlist
.- Description: The list of items to be stored.
#
Code Example#
ReturnsReturns a promise which resolves to the put items on a successful insert, and raises an error if you attempt to put more than 25 items.
PutMany(items interface{}) ([]string, error)
#
Parameters:- items: a slice of items, each item in the slice similar to the
item
parameter inPut
#
Code Example:#
ReturnsReturns the list of keys of the items stored and an error
. In case of an error, none of the items are stored. Possible error values:
ErrTooManyItems
: if there are more than 25 itemsErrBadItem
: bad item/items, one or more item of unexpected typeErrBadRequest
: one or more item caused a bad request response from the serverErrUnauthorized
: unauthorizedErrInternalServerError
: internal server error
#
Updateupdate
updates an existing item from the database.
- JavaScript
- Python
- Go
async update(updates, key)
#
Parameters- updates (required) - Accepts:
object
(JSON serializable)- Description: a json object describing the updates on the item
- key (required) – Accepts:
string
- Description: the key of the item to be updated.
#
Update operationsSet :
Set
is practiced through normal key-value pairs. The operation changes the values of the attributes provided in theset
object if the attribute already exists. If not, it adds the attribute to the item with the corresponding value.Increment:
Increment
incrementes the value of an attribute. The attribute's value must be a number. The utilbase.util.increment(value)
should be used to increment the value. The default value is 1 if not provided and it can also be negative.Append:
Append
appends to a list. The utilbase.util.append(value)
should be used to append the value. The value can be aprimitive type
or anarray
.Prepend:
Prepend
prepends to a list. The utilbase.util.prepend(value)
should be used to prepend the value. The value can be aprimitive type
or anarray
.Trim:
Trim
removes an attribute from the item, the utilbase.util.trim()
should be used as the value of an attribute.
#
Code ExampleConsider we have the following item in a base const users = deta.Base('users')
:
Then the following update operation :
Results in the following item in the base:
#
ReturnsIf the item is updated, the promise resolves to null
. Otherwise, an error is raised.
update(updates:dict, key:str)
#
Parameters- updates (required) - Accepts:
dict
(JSON serializable)- Description: a dict describing the updates on the item
- key (required) – Accepts:
string
- Description: the key of the item to be updated.
#
Update operationsSet :
Set
is practiced through normal key-value pairs. The operation changes the values of the attributes provided in theset
dict if the attribute already exists. If not, it adds the attribute to the item with the corresponding value.Increment:
Increment
incrementes the value of an attribute. The attribute's value must be a number. The utilbase.util.increment(value)
should be used to increment the value. The default value is 1 if not provided and it can also be negative.Append:
Append
appends to a list. The utilbase.util.append(value)
should be used to append the value. The value can be aprimitive type
or alist
.Prepend:
Prepend
prepends to a list. The utilbase.util.prepend(value)
should be used to prepend the value. The value can be aprimitive type
or alist
.Trim:
Trim
removes an attribute from the item, the utilbase.util.trim()
should be used as the value of an attribute.
#
Code ExampleConsider we have the following item in a base users = deta.Base('users')
:
Then the following update operation:
Results in the following item in the base:
#
ReturnsIf the item is updated, returns None
. Otherwise, an exception is raised.
Update(key stirng, updates Updates) error
#
Parameters- key: the key of the item to update
- updates : updates applied to the item, is of type
deta.Updates
which is amap[string]interface{}
#
Update operationsSet :
Set
is practiced through normal key-value pairs. The operation changes the values of the attributes provided if the attribute already exists. If not, it adds the attribute to the item with the corresponding value.Increment:
Increment
incrementes the value of an attribute. The attribute's value must be a number. The utilBase.Util.Increment(value interface{})
should be used to increment the value. The value can also be negative.Append:
Append
appends to a list. The utilBase.Util.Append(value interface{})
should be used to append the value. The value can be a slice.Prepend:
Prepend
prepends to a list. The utilBase.Util.Prepend(value interface{})
should be used to prepend the value. The value can be a slice.Trim:
Trim
removes an attribute from the item, the utilBase.Util.Trim()
should be used as the value of an attribute.
#
Code ExampleConsider we have the following item in a base users
:
Then the following update operation :
Results in the following item in the base:
#
ReturnsReturns an error
. Possible error values:
ErrBadRequest
: the update operation caused a bad request response from the serverErrUnauthorized
: unauthorizedErrInternalServerError
: internal server error
#
FetchFetch retrieves a list of items matching a query. It will retrieve everything if no query is provided.
A query is composed of a single query object or a list of queries.
In the case of a list, the indvidual queries are OR'ed.
- JavaScript
- Python
- Go
async fetch(query, pages=10, buffer=null)
#
Parameters- query: is a single query object or list of queries. If omitted, you will get all the items in the database (up to 1mb).
- pages how many pages of items should be returned.
- buffer: the number of items which will be returned for each iteration (aka "page") on the return iterable. This is useful when your query is returning more than 1mb of data, so you could buffer the results in smaller chunks.
#
Code ExampleFor the examples, let's assume we have a Base with the following data:
... will come back with following data:
myFirstSet
:#
mySecondSet
:#
#
ReturnsA promise which resolves to a generator of objects that meet the query
criteria.
The total number of items will not exceed the defined using buffer
and `pages. Max. number of items
Iterating through the generator yields arrays containing objects, each array of max length buffer
.
#
Example using buffer, pagesfetch(query=None, buffer=None, pages=10):
#
Parameters- query: is a single query object (
dict
) or list of queries. If omitted, you will get all the items in the database (up to 1mb). - pages how many pages of items should be returned.
- buffer: the number of items which will be returned for each iteration (aka "page") on the return iterable. This is useful when your query is returning more 1mb of data, so you could buffer the results in smaller chunks.
#
Code ExampleFor the examples, let's assume we have a Base with the following data:
... will come back with following data:
my_first_set
:#
my_second_set
:#
#
ReturnsA generator of objects that meet the query
criteria.
The total number of items will not exceed the defined using buffer
and `pages. Max. number of items
Iterating through the generator yields lists containing objects, each list of max length buffer
.
#
Example using buffer, pagesFetch(i *FetchInput) error
#
Parametersi: is a pointer to a
FetchInput
Q
: fetch query, is of typedeta.Query
which is a[]map[string]interface{}
Dest
: the results will be stored into the value pointed byDest
Limit
: the maximum number of items to fetch, value of0
or less applies no limitLastKey
: the last key evaluated in a paginated response, leave empty if not a subsequent fetch request
#
Code Example... results
will have the following data:
#
Paginated example#
ReturnsReturns an error
. Possible error values:
ErrBadDestination
: bad destination, results could not be stored ontodest
ErrBadRequest
: the fetch request caused a bad request response from the serverErrUnauthorized
: unauthorizedErrInternalServerError
: internal server error
#
QueriesQueries are regular objects/dicts/maps with conventions for different operations.
#
Equal#
Not Equal#
Less Than#
Greater Than#
Less Than or Equal#
Greater Than or Equal#
Prefix#
Range#
Contains#
Not Containsnote
?contains
and ?not_contains
only works for a list of strings if checking for membership in a list; it does not apply to list of other data types. You can store your lists always as a list of strings if you want to check for membership.
#
Contacthello@deta.sh