Zero Labs
Industry News / AI

Neo4j in FastAPI

Source · Towards AI By Mohit Singh Kushwaha

From the publisher’s feed, collected in the ZeroLabs newsroom.

Neo4j and FastAPINeo4j is a native graph database. It stores and represents data in graph format through nodes and relationships (aka links). The relationships have directions and mark source & destination nodes. These nodes and relationships have one or more properties associated with them. Neo4j also has most of the capabilities of a traditional database. You can define constraints & indexes, execute transactions, run subqueries, etc. You can also integrate Neo4j with RAG systems to provide structured context.Read more about Neo4jFastAPI is a modern and ‘fast’ web framework for building APIs with Python. It supports automatic documentation creation and follows OpenAPI standards. You can easily implement validations and enjoy unlimited plugins.Read more about FastAPIIn a traditional backend system, when an API is triggered, it generally makes a query in the database and returns the result. A similar architecture can be implemented with FastAPI as the backend framework and Neo4j as the database. Here, you’ll implement multiple HTTP APIs to perform different operations in Neo4j.PrerequisiteNeo4j Aura DB details (URI, Database Name, Username & Password).Python 3.14.9 virtual environmentBasic Implementation of FastAPIhttps://medium.com/media/36e3f27b3d23c2350b31493bb433dfd4/hrefi. Import the required packages.ii. Initialize the FastAPI app.iii. Configure middleware for APIsiv. Create a GET APIv. Start the serverHow to start the server-i. Save the file with the name main.py (or any other name).ii. Open the terminal and initialize the Python virtual environment.# Create virtual environment with the name ".venv"python -m venv .venv# Activate the virtual environment.venv\Scripts\activate.batiii. Run the command below to install the required packages listed in requirements.txt file.pip install -r requirements.txtYou can find a suitable requirements.txt file at this link.iv. Once the packages are installed, run the server file. Although you can run the server with python main.py, an improvement could be to use fastapi dev. This will start your server in development mode. You can also access the interactive API documentation provided by SwaggerUI.fastapi devv. This will start your server locally on port 8000. Open http://localhost:8000/docs to access the automatically created interactive documentation.Establish a connection with the Neo4j Instancei. Import the required packages from Neo4j and provide database details & credentials to initialize the driver instance. You can find the database details on the Neo4j Aura Instance page.from neo4j import GraphDatabase# Connect to Neo4j databaseNEO4J_URI = '...'NEO4J_USERNAME = '...'NEO4J_PASSWORD = '...'NEO4J_DATABASE= '...'# Initialize the driverdriver = GraphDatabase.driver( NEO4J_URI, auth=( NEO4J_USERNAME, NEO4J_PASSWORD ))ii. With the database driver initialized, call the built-in verify_connectivity() method to verify the database connection. You should perform this verification inside the main block. You can also put the code to start the server inside the same main block.def verify_neo4j_connection(): global driver try: driver.verify_connectivity() return "Neo4j verify connection successful." except: driver.close() return "Neo4j verify connection failed. Check the NEO4J_URI, NEO4J_USERNAME, and NEO4J_PASSWORD values in .env file."if __name__ == "__main__": # Verify Neo4j Connection conn_status = verify_neo4j_connection() print("Status: ", conn_status) # Run local server import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)Next, you need to implement APIs and make queries to the Neo4j database.APIs with Neo4j Queriesi. Create a GET API (“/customer/all”)ii. Create a function that will be called when this API is triggerediii. Inside the defined function, execute a query that will fetch the list of names of Customers who have Placed an Order. The execute_query() method of the Neo4j driver is used to execute queries. It takes a minimum of two parameters: the query and the database name. You can also create the query with dynamic values by passing them as additional parameters to the execute_query() method.iv. The API will return the customer name list.The Neo4j driver supports queries in the Cypher query language. It is close to natural language and visually matches the patterns and relationships in its syntax.Read more about Cypher# Get All Customers@app.get("/customer/all")def get_all_customers(): try: # Use Neo4j driver and execute query # Below query will fetch the list of names of customers who haved placed an order # -> Nodes: Customer, Order # -> Relationship: Placed records, summary, keys = driver.execute_query(""" MATCH (c:Customer)-[:PLACED]->(:Order) RETURN c.name AS name """, database_=NEO4J_DATABASE, ) # Loop through results and do something with them for record in records: print(record.data()) # obtain record as dict # Summary information print("The query `{query}` returned {records_count} records in {time} ms.".format( query=summary.query, records_count=len(records), time=summary.result_available_after )) # Return the query response return records except: return {'error': 'Something went wrong'}Call the APIOnce the above changes are done, you can visit http://localhost:8000/docs and trigger the ‘customer/all’ API from the interactive UI. It will return a list of customer names.SwaggerUI DocumentationClose the Database DriverDatabase drivers are resource-intensive. Unless you really need it, initialize only a single instance of the database driver. Also, when the server stops, properly release all resources, including the database driver.You can implement driver-closing logic inside the FastAPI shutdown event listener.# FastAPI 'shutdown' Event@app.on_event("shutdown")async def shutdown_event(): # close the database driver driver.close() print('Neo4j Driver Closed')After completing the above-discussed steps, your main.py file will look something like this-https://medium.com/media/40dbe7d0e7354642aa71f25e751b3dff/hrefFew More APIsGet CustomerGet details of the customer with the provided name who has placed an order. The API will return all the details of the customer.# Get Customer@app.get("/customer/")def get_customer(name: str = 'George'): try: records, summary, keys = driver.execute_query(""" MATCH (c:Customer {name: $name})-[:PLACED]->(:Order) RETURN c """, name=name, database_=NEO4J_DATABASE, ) # Summary information print("The query `{query}` returned {records_count} records in {time} ms.".format( query=summary.query, records_count=len(records), time=summary.result_available_after )) return records except: return {'error': 'Something went wrong'}Update CustomerUpdate the email of the customer with the provided name who has placed an order. The API will return a success message.# Update Customer@app.put("/customer")def update_customer(name: str = 'George', email: str = 'George_Anderson62@yahoo.com'): try: records, summary, keys = driver.execute_query(""" MATCH (c:Customer {name: $name}) SET c.email = $email """, name=name, email=email, database_=NEO4J_DATABASE, ) print(f"Query counters: {summary.counters}.") return {'status': 'success'} except: return {'error': 'Something went wrong'}Create CustomerCreate a new customer with the provided name & email. Since this customer will be newly created, it won’t have any relationships like :PLACED, etc. The API will return the count of nodes (customers) created.# Create Customer@app.post("/customer")def post_customer(name: str, email: str): try: joined_date = datetime.now() customer_id = f"customer{random.randrange(100,1000)}" records, summary, keys = driver.execute_query(""" CREATE (c:Customer {name: $name, email: $email, joinedDate: $joined_date, customerId: $customer_id}) """, name=name, email=email, joined_date=joined_date,customer_id=customer_id, database_=NEO4J_DATABASE, ) print("Created {nodes_created} nodes in {time} ms.".format( nodes_created=summary.counters.nodes_created, time=summary.result_available_after )) return {'nodes': summary.counters.nodes_created} except: return {'error': 'Something went wrong'}Delete CustomerDelete the customer with the provided name and all its relationships. The API will return the count of nodes deleted.# Delete Customer@app.delete("/customer")def delete_customer(name: str): try: records, summary, keys = driver.execute_query(""" MATCH (c:Customer {name: $name}) DETACH DELETE c """, name=name, database_=NEO4J_DATABASE) print("Deleted {nodes_deleted} nodes in {time} ms.".format( nodes_deleted=summary.counters.nodes_deleted, time=summary.result_available_after )) return {'nodes': summary.counters.nodes_created} except: return {'error': 'Something went wrong'}These are just some very simple examples of different HTTP methods and how they can be integrated with the Neo4j database. There are still an enormous number of features to be explored.Visit Neo4j Docs and learn more!Check out my git repo: Neo4j — FastAPI IntegrationNeo4j in FastAPI was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.