How to query Weaviate with GraphQL
Quick answer
Use Weaviate's GraphQL endpoint by sending HTTP POST requests with a GraphQL query string in JSON format. In Python, use the
requests library to post queries to http://localhost:8080/v1/graphql or your Weaviate instance URL and parse the JSON response.PREREQUISITES
Python 3.8+Weaviate instance running (local or cloud)pip install requests
Setup
Install the requests library to send HTTP requests to Weaviate's GraphQL endpoint. Ensure your Weaviate instance is running and accessible.
pip install requests Step by step
This example shows how to query Weaviate's GraphQL API to fetch objects of a class with specific properties.
import os
import requests
# Set your Weaviate URL (local or cloud)
WEAVIATE_URL = os.environ.get('WEAVIATE_URL', 'http://localhost:8080')
# Define the GraphQL query to fetch objects from a class named 'Article'
graphql_query = '''
{
Get {
Article {
title
url
content
}
}
}
'''
# Prepare the request payload
payload = {"query": graphql_query}
# Send POST request to Weaviate GraphQL endpoint
response = requests.post(f"{WEAVIATE_URL}/v1/graphql", json=payload)
# Check for successful response
response.raise_for_status()
# Parse JSON response
data = response.json()
# Print fetched data
print(data) output
{'data': {'Get': {'Article': [{'title': 'Example Title', 'url': 'https://example.com', 'content': 'Sample content text.'}]}}} Common variations
You can customize your GraphQL queries to filter, limit, or include nearVector searches for semantic similarity. For example, add where filters or nearVector arguments inside the Get block.
Example with nearVector:
graphql_query_near_vector = '''
{
Get {
Article(
nearVector: {
vector: [0.1, 0.2, 0.3, 0.4],
certainty: 0.7
},
limit: 3
) {
title
url
}
}
}
'''
payload = {"query": graphql_query_near_vector}
response = requests.post(f"{WEAVIATE_URL}/v1/graphql", json=payload)
response.raise_for_status()
data = response.json()
print(data) output
{'data': {'Get': {'Article': [{'title': 'Related Article 1', 'url': 'https://example.com/1'}, {'title': 'Related Article 2', 'url': 'https://example.com/2'}]}}} Troubleshooting
- If you get a connection error, verify your Weaviate instance URL and that the server is running.
- If the response contains errors, check your GraphQL query syntax and class names.
- For authentication-enabled Weaviate instances, include the
Authorizationheader with your API key in the request.
headers = {
"Authorization": f"Bearer {os.environ.get('WEAVIATE_API_KEY', '')}"
}
response = requests.post(f"{WEAVIATE_URL}/v1/graphql", json=payload, headers=headers)
response.raise_for_status() Key Takeaways
- Use HTTP POST with JSON payload to query Weaviate's GraphQL endpoint.
- Customize queries with filters, limits, and nearVector for semantic search.
- Include Authorization headers if your Weaviate instance requires authentication.