You are currently viewing How to Create a Database in Appwrite Using Python

How to Create a Database in Appwrite Using Python

Appwrite is an open-source backend platform that reduces a developer’s effort and time spent building a backend server from scratch. It is a backend-as-a-service solution that handles backend tasks for web, mobile, and Flutter apps.

Appwrite offers databases, authentication, storage, real-time communication, and many other services.

Creating and configuring a database in a web app is time-consuming, and this tutorial will walk you through the process of doing so in simple steps using Appwrite’s Python SDK (Software Development Kit) or package.

If you don’t want to deal with preliminary tasks before setting up the database in the Appwrite cloud, you can skip to the database creation section.

Collecting Required Info

Before you begin creating a database on the Appwrite cloud, you must first obtain the following credentials from the Appwrite console:

  • Appwrite API key
  • Appwrite Project ID
  • Appwrite Cloud API Endpoint

Step 1: Obtaining Project ID

  • To gain access to the Appwrite console, create an account on the Appwrite cloud (https://cloud.appwrite.io/) or log in if you already have one.
  • Click the “Create project” button, give your project a name, and then save the “Project ID”.
Project Creation and Saving Project ID

Step 2: Obtaining API Key

  • After you’ve created a new project, scroll down and click the “API Key” button.
  • Fill in the API name and select the expiration time, then click the “Next” button, then add the scope “Database”, and finally click the “Create” button.
API Key Setup
  • Scroll down the Appwrite console and click on “API Keys” under the “Integrations” section, followed by your newly created API name.
  • Copy the project’s API Key by clicking on the “API Key Secret” button.
API Key Secret

Installing Appwrite’s Python Package

Using Python to create a database on the Appwrite cloud requires a Python package called appwrite, which provides API access to interact with the Appwrite backend and perform various tasks.

Open a terminal window and type the following command to install the Python package appwrite with pip.

Creating a Database

Creating a database on the Appwrite cloud involves simple steps. With all the required credentials gathered, let’s create a database using Python.

Importing Required Modules

from appwrite.client import Client: To interact with the Appwrite API, the Client class is imported from the appwrite.client module. The Client class will allow you to configure the API key, Project ID, and API endpoint for making Appwrite backend requests.

from appwrite.services.databases import Databases: To work with Database on the Appwrite cloud, the Databases class is imported from the appwrite.services.databases module.

from appwrite.id import ID: To generate unique IDs that can be used within Appwrite, the ID class is imported from the appwrite.id module.

import os: To interact with the operating system, the os module is imported.

from dotenv import load_dotenv: To load environment variables to the Python file. The library can be installed with pip install python-dotenv, if it is not installed.

Configuring the Appwrite Client for API Access

Instantiating Appwrite Client: The Client class instance is created and stored in the client variable.

The environment variables (PROJECT_ID and API_KEY) are loaded into the script using the load_dotenv() function.

Setting API Endpoint: The Appwrite client’s set_endpoint() method is used to set the API endpoint to the URL 'https://cloud.appwrite.io/v1'.

Setting Project ID: The Appwrite client’s set_project() method is used to set the Project ID of the project by retrieving it from the environment variable 'PROJECT ID' using os.getenv('PROJECT ID').

Setting API Key: Similarly, the API key is set with the set_key() method, and it was retrieved from the environment variable 'API_KEY' with os.getenv('API_KEY').

Creating a New Database

The Databases instance is created with Databases(client) and saved in the databases variable. This enables interaction with the Appwrite Database API and the execution of various database-related tasks.

The ID.unique() method is used to generate a unique ID for the database, which is then stored in the db_id variable.

The code then creates a database by calling the databases.create() method, which takes two parameters: the database ID in this case, db_id, and the database name, which in this case is 'BooksDB'.

If you run the file, the database will be created and will be visible on the Appwrite cloud.

Database Created

Creating a database is not sufficient, especially if you intend to connect it to a web app. It’s required for CRUD operations like adding new data, updating it, reading it, and even deleting it.

To create a fully functional database for data storage, the following must be created:

  • Collections
  • Attributes
  • Documents

Creating Collections

Collections in the Appwrite database are data storage containers similar to tables in traditional databases.

You can create multiple collections in a single Appwrite database to store and manage data from various sources, which will aid in data management.

The database ID is retrieved using create_db['$id'] and stored in the database_id variable.

The ID.unique() method is used to generate a unique ID for the collection in the database and the resulting ID is stored in the collection_id variable.

To create a new collection, the databases.create_collection() method is used. It accepts three required arguments: database_id, which represents the ID of the database where the collection will be created, collection_id, a unique ID to ensure no conflicts with existing collections, and name, which specifies the name of the new collection, which is "Books" in this case.

Collection Created

Creating Attributes

Following the completion of collections, the next step is to create attributes. The attributes define the schema of the data. Attributes are of different types, you can choose as per requirement.

Attributes are similar to fields in a traditional database table, where data is stored under the respective field. This ensures a standardized structure of the documents in the Appwrite database.

Since the database is for Book details, the schema will be as follows:

  • id – integer: Used to store the book’s ID.
  • image – url: Book image
  • title – string: The title of the book
  • author – string: The author of the book
  • genre – string: The book’s genre

The attributes will be generated based on the fields listed above.

The create_integer_attribute() method is used to create the integer attribute “id” for the “Books” collection. This method is invoked with four mandatory arguments: database_id (set to database_id), collection_id (set to c_id), key (set to "id" as the attribute name), and required (set to True to indicate that the value of this attribute cannot be left empty).

The create_url_attribute() method is used to create the URL attribute “image” for the “Books” collection. This method is also called with four mandatory arguments: database_idcollection_idkey set to "image", and required parameter set to True.

Finally, the create_string_attribute() method is used to create three string attributes, namely “title”“author”, and “genre” for the “Books” collection. This method requires five parameters: database_idcollection_idkeyrequired, and size, which is the maximum number of characters allowed for the attribute.

Attributes Created

Now that all processes have been completed and the database is ready, you can add data from the frontend and store it as documents within the database.

Adding Documents

Following the schema that was created in the previous section, data will be added programmatically within the collection called “Books” in the database called “BooksDB” in this section.

The code defines an add_doc function that takes a single argument named document. Within the function’s try block, the databases.create_document() method is invoked to generate a document, which is subsequently stored in the doc variable.

This method requires four mandatory parameters: database_id (set as database_id), collection_id (set as c_id), document_id (representing a unique ID for the document, specifically assigned as document_id), and data (representing the document’s content formatted in a dictionary).

The doc variable stores a dictionary returned by the databases.create_document(). Utilizing this doc variable, the code retrieves the idimagetitleauthor, and genre of the added document and prints them.

If an exception arises during the try block’s execution, the code captures the error and displays an error message.

Data

When you run the whole code, the following output will be prompted and the database, collection, and attributes will be created and documents will then be added.

Documents Added

Source Code

Access the full source code from the following GitHub repository, clone or download the code and run it in your favorite IDE.

Python Script For Creating Appwrite Database

Conclusion

The tutorial walked you through the steps of setting up a new database in the Appwrite cloud. It also includes instructions for creating a new project, creating an API key for the project, and obtaining the project ID and API key from the Appwrite cloud.

Following the creation of the database, the tutorial takes you through the steps of making it fully functional by adding collections and attributes. The documents (data) are then added programmatically.

Let’s go over the steps in this tutorial for creating a new database:

  • Obtaining the necessary Appwrite cloud credentials
  • Installing the Python package appwrite
  • Making a database
  • Making a collection
  • Adding the attributes
  • Adding the documents programmatically

πŸ†Other articles you might be interested in if you liked this one

βœ…How to connect the PostgreSQL database with Python?

βœ…Upload and display images on the frontend using Flask in Python.

βœ…Building a Flask image recognition webapp using a deep learning model.

βœ…Building a custom deep learning model using transfer learning.

βœ…How to augment the data for training using Keras and Python?

βœ…How to build a CLI command in a few steps using argparse in Python?

βœ…How to use Async/Await like JavaScript in Python?

βœ…How to scrape a webpage’s content using BeautifulSoup in Python?


That’s all for now

Keep Coding✌✌