Building a Python Web Application Using Flask and Neo4j

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up Flask and Neo4j
  4. Creating the Flask Application
  5. Creating Routes
  6. Working with Neo4j
  7. Conclusion

Introduction

In this tutorial, we will learn how to build a Python web application using the Flask framework and the Neo4j graph database. Flask is a lightweight web framework written in Python, and Neo4j is a highly scalable native graph database. By the end of this tutorial, you will have a basic understanding of how to create a web application that interacts with a graph database, allowing you to build powerful and dynamic applications.

Prerequisites

Before getting started, make sure you have the following:

  • Python installed on your machine
  • Flask and Neo4j libraries installed (use pip install flask neo4j to install them)
  • Basic knowledge of Python programming

Setting Up Flask and Neo4j

  1. Create a new directory for your project and navigate to it using the command line.
  2. Create a virtual environment by running the command python -m venv venv.
  3. Activate the virtual environment by running source venv/bin/activate (for Mac/Linux) or venv\Scripts\activate (for Windows).
  4. Install Flask and Neo4j libraries by running pip install flask neo4j.

Creating the Flask Application

  1. Create a new Python file called app.py in your project directory.
  2. Import the necessary libraries:
     from flask import Flask, render_template, request
     from neo4j import GraphDatabase
    
  3. Initialize the Flask application:
     app = Flask(__name__)
    
  4. Set up the Neo4j driver:
     driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
    

    Replace "bolt://localhost:7687" with the Neo4j address and port, and "neo4j" and "password" with your Neo4j credentials.

  5. Define a route to the home page:
     @app.route("/")
     def home():
         return "Hello, Flask!"
    
  6. Run the Flask application:
     if __name__ == "__main__":
         app.run()
    

    Save the file and run it using the command python app.py. You should see the message “Hello, Flask!” when you visit http://localhost:5000 in your web browser.

Creating Routes

Now that we have the basic Flask application set up, let’s create some routes to handle different pages of our web application.

  1. Define a route to display a form for adding a new user:
     @app.route("/user/add", methods=["GET"])
     def add_user_form():
         return render_template("add_user.html")
    
  2. Create a new HTML file called add_user.html in a templates directory in your project. Add the following form:
     <!DOCTYPE html>
     <html>
     <head>
         <title>Add User</title>
     </head>
     <body>
         <h1>Add User</h1>
         <form action="/user/add" method="POST">
             <label for="name">Name:</label>
             <input type="text" name="name" id="name">
             <br>
             <input type="submit" value="Submit">
         </form>
     </body>
     </html>
    
  3. Define a route to handle the form submission and add the user to the database:
     @app.route("/user/add", methods=["POST"])
     def add_user():
         name = request.form.get("name")
    	    
         with driver.session() as session:
             session.run("CREATE (u:User {name: $name})", name=name)
    	    
         return "User added successfully!"
    

    Now when you visit http://localhost:5000/user/add, you should see a form to add a new user. Submitting the form will add the user to the Neo4j database.

Working with Neo4j

We have successfully created a route to add a user to our Neo4j database. Let’s now create a route to retrieve and display all the users.

  1. Define a route to display all users:
     @app.route("/users", methods=["GET"])
     def get_users():
         with driver.session() as session:
             result = session.run("MATCH (u:User) RETURN u.name AS name")
             users = [record["name"] for record in result]
    	    
         return render_template("users.html", users=users)
    
  2. Create a new HTML file called users.html in the templates directory and add the following code:
     <!DOCTYPE html>
     <html>
     <head>
         <title>Users</title>
     </head>
     <body>
         <h1>Users</h1>
         <ul>
    	        
         </ul>
     </body>
     </html>
    

    Now, when you visit http://localhost:5000/users, you should see a list of all the users stored in the Neo4j database.

Conclusion

Congratulations! You have successfully built a Python web application using Flask and Neo4j. In this tutorial, we learned how to set up Flask and Neo4j, create routes, and interact with a graph database. You can now use this knowledge to build more complex web applications that leverage the power of Neo4j to handle and visualize relationships between data.

In this tutorial, we covered the basics of Flask and Neo4j, but there are many more features and functionalities to explore. Consider exploring Flask’s documentation and the Neo4j Python driver documentation to dive deeper into these technologies. Happy coding!