Python Neo4j Code Driver
The code shown uses the official Neo4j Python Driver and can be found in this gist: https://gist.github.com/jalakoo/9e0ff836bc75e1a2b9945baf2eede4c4
This example uses a public demo database with the goodreads dataset containing Book nodes and their related entities.

Create a project file
Create a file named app.py.
Next create a virtual environment, start it, and pull down the neo4j driver:
python -m venv venv source venv/bin/activate pip install neo4j
Connect to the database
In the app.py file, to connect to Neo4j, you need the connection URI, username, password, and the name of the database. In this sample, credentials for the demo server are provided.
from neo4j import GraphDatabase # Read-only credentials URI = "neo4j+s://demo.neo4jlabs.com" USERNAME = "goodreads" PASSWORD = "goodreads" DATABASE = "goodreads"
The neo4j+s:// scheme ensures an encrypted connection to the database.
Running a query
The execute_query API is the recommended way to run queries with the Python driver. It automatically manages sessions, transactions, and retries, reducing boilerplate code.
In this sample, we define a main function that accepts a Cypher query and a dictionary of parameters.
# 1. Using the new `execute_query` API
def main(query, params):
with GraphDatabase.driver(URI, auth=(USERNAME, PASSWORD)) as driver:
records, summary, keys = driver.execute_query(
query,
parameters_ = params,
database_ = DATABASE
)
# Convert records into Python dictionaries
return [record.data() for record in records]
The method returns three values:
- records → the actual query results
- summary → metadata about the query execution (like how many results were returned)
- keys → the property names returned by the query
Most of the time, you’ll be interested only in the records. Here, each record is converted to a dictionary for easier use in Python.
Example query
The following example creates or reuses a Book node with the given title and returns up to 10 results.
if __name__ == "__main__":
query = """
MERGE (b:Book {title: $title})
RETURN b.title as title
LIMIT $limit
"""
params = {
"title": "The Great Gatsby",
"limit": 10
}
print(main(query, params))
When executed, this script will print a list of dictionaries containing book titles, showing how to pass parameters and retrieve results.
Run the script
You can run the script from the command line with:
python neo4j_example.py
Replace neo4j_example.py with the filename where you saved the code.
Resources
- Code: Neo4j Python Driver GitHub
- Documentation: Neo4j Python Driver Manual
- GraphAcademy courses: https://graphacademy.neo4j.com/categories/?search=python


