A Definitive Guideline for Creating APIs with Django and Neo4j database, Part-1
Tags: beginners, django, python, tutorial
Published: 2023-08-24 21:44:22

In this post, we will work on our graph database and setup all the necessary connections for building our APIs. As the name suggests, we will be using Neo4j database for our project. The entire architecture for this project is like this, courtesy to this (only) [link](https://medium.com/swlh/create-rest-api-with-django-and-neo4j-database-using-django-nemodel-1290da717df9) on the subject matter:


![Architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c8f8qlzb4l7rd9lnvfxq.png)

Today, we will tear down the rightmost part of this diagram - Neo4j database and the model. Basically, we are using Django framework to provide the API URLs and what each URL will serve. The steps are as follows:

1. Download and install Neo4j
2. Download cypher-shell and update credentials
3. Setup Remote Database connection
4. Setup database connection with Django
5. Manipulate OGM
6. Migrate the database

## 1. Download and install Neo4j

Go to the official website of Neo4j and download the desktop application - [here](https://neo4j.com/deployment-center/#desktop), and sign up an account. You will be provided with an activation key while downloading, copy it paste it during installation. 

## 2. Download cypher-shell and update credentials

This is an optional step. Cypher shell provides you with a console where you can write CQL or Cypher Query Language, just like a python shell. You can download this from here - [Official Download Link](https://neo4j.com/docs/operations-manual/current/tools/cypher-shell/#:~:text=The%20cypher%2Dshell%20files%20are,Shell%20from%20Neo4j%20Download%20Center.). 

The default graph database in free version is **neo4j** with the password **neo4j**. You can change the password with the following command:

```{Cypher}
ALTER USER neo4j SET PASSWORD '<new-password>';

```
Mark this new password because it is needed for setting up the connection with the database.

## 3. Setup Remote Database connection

- Go to  **Projects**:
![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sspw8kosxqhni5uwaafp.png)

- Create a new project with a name :
![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/if4pvcy2lwcmjg1tn6ow.png)

- There is a dashboard for your project that looks like this:
![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i37igfeqqyxv55a7wknf.png)

- Click **Add** and then the marked menu item:
![4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nb4nkt2uwox2bx1byz7o.png)

- Give a DBMS name and set the url like the format shown in the picture, then click **Next**:
![5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l491eqcn5w8bluhck7qn.png)

- Provide your database username and password, then click **save**:
![6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o8lsj9i3tzzhazzfvvhb.png)

- Click **Connect** to set the connection with the database:
![7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxncw7hcc0t2a32ha2bd.png)

- Click **Open** to see in the browser:
![8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77gjayw9nuxu407tbwim.png)

- In the Browser, click the **green highlighted db** icon:
![9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxm4iqd698cyle97fgix.png)

- Select neo4j and it will now show the default movie table. 

![10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w379c9i1z5fh31kypz0j.png)

## 4. Setup database connection with Django

First, create a Django project and then create an app inside the project for the APIs.

```{python}
django-admin startproject mysite
cd mysite/
python manage.py startapp yourapp

```

Now go to your settings.py and import config from neomodel. This is required to set up our database with Django. Your console should look like this:


![django1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e10p769y10fuqfe40tp0.png)

Go to your settings.py and the following lines in the respective places: 

```{python}
from neomodel import config

config.DATABASE_URL = 'bolt://username:password@localhost:7687'

# you can either use bolt or neo4j for the connection type but bolt is preferable

```
Replace the username and the password with yours. 

## 5. Manipulate OGM

From Django's official documentation, "Once you've created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects." - this is the ORM or **object-relational mapping layer**. To break it down in simpler terms, Django models are like a mirror to your database; it models your database tables with its own abstraction layer. Your API requests are passed through this abstraction layer under the hood. 

As we are using a graph database, we have nodes instead of tables and edges to capture the relationship. Neo4j provides OGM or **object-graph mapping library** with Neo4j-OGM. To use this, first import the field types and follow this code:

```{python}

from neomodel import StructuredNode, StringProperty, IntegerProperty,UniqueIdProperty, RelationshipTo, BooleanProperty, EmailProperty, DateTimeProperty, DateProperty, config

class NeoUser(StructuredNode):
    uid = UniqueIdProperty()
    username = StringProperty()
    email = EmailProperty(unique_index=True)
    password = StringProperty()

class NeoPosts(StructuredNode):
    ....

```

To design the relationship, You have to write like the following (refer to ERD from the previous blog post):

```
# Relations :
    post = RelationshipTo(NeoPosts, 'CREATES')
    followers = RelationshipTo('NeoUser','FOLLOWERS')
```


## 6. Migrate the database

For Django models, you were supposed to run the following commands.

```{python}
python manage.py makemigrations
python manage.py migrate

```

However, since we are making nodes in this model, we need to use the following command:

```{python}
python manage.py install_labels

```

Now you can view your created model and the nodes like the following image: 

![11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7uplrdncm4ugd9y8u8u2.png)

That's it for this post. In the next post, we will learn to build the APIs for the model that we have built. I will publish the next part soon. Your feedback is highly appreciated.