Python for FaunaDB
Tags: fauna, python, database, cloudnative
Published: 2021-02-08 19:40:14


# Introduction  
  
Cloud native data APIs, serverless services and cloud native services in general are becoming a go to for companies who no longer wish to manage their own data and infrastructure layer. This use case is getting more common as startups shift their focus more towards their core business and customer satisfaction.   
  
Cloud native services ride on the already successful and proven delivery model of the cloud compute services. They are reliable, scalable and readily available. Using these,startups quickly bypass infrastructural setups such as networks, server and operating system provisions. The saved time and resources is then channelled towards their core business, thus staying competitive.  
  
In this guide, you will explore and learn about such a cloud native offering. A data API leveraging the cloud compute and serverless architecture to offer reliability, flexibility and cost savings.  The API also boasts its ability to handle different data models, from graph to document based data.  
   
# FaunaDB
[Fauna](https://fauna.com) ,a cloud native data API, marketed for developers and designed for serverless applications. Some of the outstanding features include a native graphql layer, support for different data models(relational, document or graph) and ACID transactions which ensure consistency.  
    
It follows a _freemium_ approach where one can subscribe to the free plan and later move up the tiers if need be. As a true developer centric offering, the service accommodates some popular programming languages by means of drivers.  
There are several language drivers available such as Javascript, C#, Go and Python amongst others.    
    
To get started, [register](https://dashboard.fauna.com/accounts/register?utm_source=DevTo&utm_medium=referral&utm_campaign=WritewithFauna_GettingStartedFaunaPython_KThagana) and create a new database where you will receive a database key.    
  
With the key, it is then possible to develop your app in your preferred language and use the available drivers to connect to your newly created cloud native database.  
  
The interface, upon checking the box, can load some sample data to allow you to navigate the user interface and interact with CRUD components.    


   
# Scenario  
To better understand Fauna and its use, we will create a sample app that serves the purpose from a sample scenario.  
  
Consider the situation where you are an independent software and systems consultant advising a hospital. The client (the hospital) wishes to move its operations to the cloud. Among the requirements, the client wishes to have a data layer service that is flexible enough to accommodate different data schemas. Mainly, document, graph and relational due to their data science and mining operations that they wish to perform in future.  
The client also wishes that the solution is Python friendly as this is the main language they intend to use.  
  
Taking all these requirements into consideration, over and above their desire for a reliable and cost effective solution, you choose to suggest [FaunaDB](https://fauna.com).  
   
 To demonstrate its use, you attach a sample application, written with Python drivers, to your proposal for the client's developer team to gain some insights.  
    
# Sample App  
  
To demonstrate a hospital's operations, consider the schema below  
```graphql  
Doctor  
  last_name
  first_name 
  license_number 
  specialization 
  staffID  

Diagnosis  
  doctor 
  notes 
  patient  
 
Patient  
 last_name 
 first_name 
 patientID 
 insurance_policy  
```  



## Python Driver  
To install the python driver, run the command `pip install faunadb`  
  
The source code for the driver can be found [here](https://github.com/fauna/faunadb-python)    
    
The codeblock below shows a starter script to get you going.    
```pythonstub   
import os 
from faunadb 
import query as q
from faunadb.client import FaunaClient 
   
 db_client = FaunaClient(secret=os.environ.get("secret"))  
 ```


 It is always best practice to keep keys as environment variables. In this case, the `secret` is the key to access your cloud based FaunaDB instance that you created on your dashboard.  
With the above code, you are connected and can commence performing database operations such as CRUD.  

### Create Collection  

```pythonstub  
doctor_collection = db_client.query(q.create_collection({"name":"doctors"}))  
```   
Create the remaining collections, _Diagnosis_ and _Patient_ using the above syntax  
  
### Create Document  

```pythonstub  
doctor_1 = db_client.query(    
 q.create(doctor_collection["ref"],   
  {"data":{"last_name": "Fauc",    
 "first_name":"John",   
 "license_number": "AGY5578199O",  
"specialization": "cardiologist",  
"staffID":"AW110"  
}})) 
``` 
Create document with a foreign key reference  



```pythonstub  
diagnosis_1 = db_client.query(    
 q.create(diagnosis_collection["ref"],   
  {"data":{"doctor": q.ref(q.collection("doctors"), "181019942046968320"),    
 "patient":q.ref(q.collection("patients"), "181019942046968320"),   
 "notes": "The patient seems to exhibit symptoms of the common flu....",  
}})) 
``` 
Use the above syntax to create several more records in the available collections.  
  
### Retrieve Records  
  
Demonstrate  a **retrieve** operation by getting a single doctor's document entered into the database by the create function.  

```pythonstub  
single_doctor = db_client.query(  
 q.get(q.ref(q.collection("doctors"), "181019942046968320")))  
print(single_doctor)  
```  
_Note that the second parameter after the collection is the reference number for a particular document_  
  
### Update Record  

To demonstrate an update, assume that there is a slight error in the previously created `doctor` record. 
Below is the update syntax  
```pythonstub  
updated_doc = db_client.query(  
 q.update( q.ref(q.collection("doctors"), "181388642312002080"), { "data": { "specialiation": "Cardiology", "license_number": "AGY5578199O-001" } } ))  
print(updated_doc)  
```  
### Delete Records  
```pythonstub  
record = db_client.query(  
 q.delete(q.ref(q.collection("doctors"), "182028742581742080")))  
  
```  
With the above code snippets, you have demonstrated how to perform basic CRUD operations using the Python driver for Fauna.  
  
Learn more about the various functions in the Fauna Query Language (FQL) [here](https://docs.fauna.com/fauna/current/api/fql/functions).  

# Conclusion  

Content on cloud native transactional databases or data APIs in general is best consumed by backend engineers and devops engineers.  
     
It is important for developers to be well acquainted with cloud native tools such as FaunaDB to not only allow them to build and design better applications, but to also help them stay relevant in the fast paced ever changing world of tech.  
  
It is best advised to not stop at this guide. Build your knowledge base and further pursue concepts learnt in this guide. Majorly  cloud native data APIs and FaunaDB. 
This then implies that further reading is required   to increase your understanding and grasp of the subject matter.   
Below are some related topics to pursue:  
1. Develop a Flask or Django based app using FaunaDB as your data layer. You can further develop the sample app.  
2. Fauna Query Language- Native to FaunaDB  
3. Cloud native architectures and design  
4. FaunaDB GraphQL layer for your apps and its pros and cons.  
5. Trade off between NoSQL and SQL data structures for your data stores