graphs

Query Neo4j graph database with Requests

This snippet provides a very quick example of how to send a very simple CYPHER query to Neo4j with Python:

import requests

url = "http://localhost:7474/db/data/cypher"

payload = "{ \"query\" : \"MATCH p=()-[r:CONSIDERED_BY]->() RETURN p LIMIT 25\",\n  \"params\" : { } }"
headers = {
    'authorization': "Basic bmVvNGo6Zm9vYmFy",
    'cache-control': "no-cache"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

Note that the 'authorization': "Basic bmVvNGo6Zm9vYmFy" bit in the headers {} section is a Base64 encoded representation of the username and password of my local Neo4j instance: neo4j:foobar

You can encode your own Neo4j username:password combination here: https://www.base64encode.org/

Authenticating into neo4j in a Jupyter Notebook using py2neo

I recently spend a frustrating few hours trying to replicate these examples in a Jupyter Notebook.

Every time I attempted to run this line...

graph = Graph()

... the trace would go loopy and I'd get a connection refused error. Here's how to get around this problem. 

Start Neo4j

You need a running instance of Neo4j before you even attempt to start running the code. So, either launch the desktop app or, if you prefer, launch an instance from the shell, like so,

$ neo4j start

By default, neo4j will listen on port 7474.

The authentication code

The following code can then be run inside the Notebook (or wherever) and you won't get the error I kept seeing:

from py2neo import authenticate, Graph

# set up authentication parameters
authenticate("localhost:7474", "neo4j", "Nov2015!!")

# connect to authenticated graph database
graph = Graph("http://localhost:7474/db/data/")