Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Create an Appwrite Database using only Python
Sachin
Sachin

Posted on • Originally published atgeekpython.in

     

Create an Appwrite Database using only 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 login 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 createdAPI 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 calledappwrite, 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 packageappwrite withpip.

pipinstallappwrite
Enter fullscreen modeExit fullscreen mode

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

fromappwrite.clientimportClientfromappwrite.services.databasesimportDatabasesfromappwrite.idimportIDimportosfromdotenvimportload_dotenv
Enter fullscreen modeExit fullscreen mode

from appwrite.client import Client: To interact with the Appwrite API, theClient class is imported from theappwrite.client module. TheClient 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, theDatabases class is imported from theappwrite.services.databases module.

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

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

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

Configuring the Appwrite Client for API Access

""" Configuring Appwrite Client """# Instantiating Appwrite Clientclient=Client()# To load environment variablesload_dotenv()# Configuring Appwrite Client(client# Setting API Endpoint.set_endpoint('https://cloud.appwrite.io/v1')# Setting Project ID.set_project(os.getenv('PROJECT_ID'))# Setting API Key.set_key(os.getenv('API_KEY')))
Enter fullscreen modeExit fullscreen mode

Instantiating Appwrite Client: TheClient class instance is created and stored in theclient variable.

The environment variables (PROJECT_ID andAPI_KEY) are loaded into the script using theload_dotenv() function.

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

Setting Project ID: The Appwrite client'sset_project() method is used to set the Project ID of the project by retrieving it from the environment variable'PROJECT ID' usingos.getenv('PROJECT ID').

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

Creating a New Database

""" Creating Database """# Initializing databases servicedatabases=Databases(client)# To generate unique database IDdb_id=ID.unique()# Creating a new databasecreate_db=databases.create(db_id,'BooksDB')print("Database Successfully Created.")
Enter fullscreen modeExit fullscreen mode

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

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

The code then creates a database by calling thedatabases.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.

"""Creating Collections"""# Database IDdatabase_id=create_db['$id']# For Generating Unique Collection IDcollection_id=ID.unique()# Creating a New Collectionnew_collection=databases.create_collection(database_id=database_id,collection_id=collection_id,name='Books')print('Collection Successfully Created.')
Enter fullscreen modeExit fullscreen mode

The database ID is retrieved usingcreate_db['$id'] and stored in thedatabase_id variable.

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

To create a new collection, thedatabases.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, andname, 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 differenttypes, 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 forBook 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.

"""Creating Attributes"""# Collection ID of Bookc_id=new_collection['$id']""" Creating integer attribute """# ID Attributebook_id=databases.create_integer_attribute(database_id=database_id,collection_id=c_id,key="id",required=True)""" Creating url attribute """# URL Attributebook_url=databases.create_url_attribute(database_id=database_id,collection_id=c_id,key="image",required=True)""" Creating string attribute """# Title Attributebook_title=databases.create_string_attribute(database_id=database_id,collection_id=c_id,key="title",required=True,size=100)# Author Attributebook_author=databases.create_string_attribute(database_id=database_id,collection_id=c_id,key="author",required=True,size=50)# Genre Attributebook_genre=databases.create_string_attribute(database_id=database_id,collection_id=c_id,key="genre",required=True,size=50)print("Attributes Successfully Created.")
Enter fullscreen modeExit fullscreen mode

Thecreate_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 todatabase_id),collection_id (set toc_id),key (set to"id" as the attribute name), andrequired (set toTrue to indicate that the value of this attribute cannot be left empty).

Thecreate_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_id,collection_id,key set to"image", andrequired parameter set toTrue.

Finally, thecreate_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_id,collection_id,key,required, andsize, which is the maximum number of characters allowed for the attribute.

Attributes

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.

""" Adding Documents """# Unique Identifier for Document IDdocument_id=ID.unique()""" Function for Adding Documents(data) in the Database """defadd_doc(document):try:doc=databases.create_document(database_id=database_id,collection_id=c_id,document_id=document_id,data=document)print("Id:",doc['id'])print("Image:",doc['image'])print("Title:",doc['title'])print("Author:",doc['author'])print("Genre:",doc['genre'])print("-"*20)exceptExceptionase:print(e)
Enter fullscreen modeExit fullscreen mode

The code defines anadd_doc function that takes a single argument nameddocument. Within the function'stry block, thedatabases.create_document() method is invoked to generate a document, which is subsequently stored in thedoc variable.

This method requires four mandatory parameters:database_id (set asdatabase_id),collection_id (set asc_id),document_id (representing a unique ID for the document, specifically assigned asdocument_id), anddata (representing the document's content formatted in a dictionary).

Thedoc variable stores a dictionary returned by thedatabases.create_document(). Utilizing thisdoc variable, the code retrieves theid,image,title,author, andgenre of the added document and prints them.

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

Data

# Data To Be Addedbook_1={"id":1,"image":"https://i.pinimg.com/474x/dc/17/2d/dc172d6fa3f5461d94e6d384aded2cb4.jpg","title":"The Great Gatsby","author":"F. Scott Fitzgerald","genre":"Fiction"}book_2={"id":2,"image":"https://i.pinimg.com/originals/0b/bf/b5/0bbfb59b4d5592e2e7fac9930012ce6d.jpg","title":"To Kill a Mockingbird","author":"Harper Lee","genre":"Fiction"}book_3={"id":3,"image":"https://i.pinimg.com/736x/66/1d/17/661d179ab722e67eed274d24b8965b0d.jpg","title":"Pride and Prejudice","author":"Jane Austen","genre":"Romance"}book_4={"id":4,"image":"https://i.pinimg.com/originals/68/c5/4c/68c54c9599ba37d9ab98c0c51afe2298.png","title":"Crime and Punishment","author":"Fyodor Dostoevsky","genre":"Psychological Fiction"}# Calling function with the data to be addedadd_doc(book_1)add_doc(book_2)add_doc(book_3)add_doc(book_4)print("Documents Successfully Added.")
Enter fullscreen modeExit fullscreen mode

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.

Database Successfully Created.Collection Successfully Created.Attributes Successfully Created.Id: 1Image: https://i.pinimg.com/474x/dc/17/2d/dc172d6fa3f5461d94e6d384aded2cb4.jpgTitle: The Great GatsbyAuthor: F. Scott FitzgeraldGenre: Fiction--------------------Id: 2Image: https://i.pinimg.com/originals/0b/bf/b5/0bbfb59b4d5592e2e7fac9930012ce6d.jpgTitle: To Kill a MockingbirdAuthor: Harper LeeGenre: Fiction--------------------Id: 3Image: https://i.pinimg.com/736x/66/1d/17/661d179ab722e67eed274d24b8965b0d.jpgTitle: Pride and PrejudiceAuthor: Jane AustenGenre: Romance--------------------Id: 4Image: https://i.pinimg.com/originals/68/c5/4c/68c54c9599ba37d9ab98c0c51afe2298.pngTitle: Crime and PunishmentAuthor: Fyodor DostoevskyGenre: Psychological Fiction--------------------Documents Successfully Added.
Enter fullscreen modeExit fullscreen mode

Documents

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 packageappwrite

  • 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✌✌

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A Python developer obsessed with Machine Learning and Data Science.
  • Location
    Delhi
  • Joined

More fromSachin

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp