Using Defog for querying your database
1. Create your API Key
If you are seeing this message, your API key has not been created. Please sign up to a paid plan to get your API key
2. Set up your database type and metadata on Defog
Postgres
Python
# run "pip install --upgrade defog" to install the defog package
from defog import Defog
defog = Defog(
api_key = "YOUR_API_KEY",
db_type = "postgres",
db_creds = {
"host": "YOUR_DB_HOST",
"port": YOUR_DB_PORT,
"database": "YOUR_DB_NAME",
"user": "YOUR_DB_USER",
"password": "YOUR_DB_PASS"
}
)
tables=["table1", "table2", "table3", ...] # list of tables you want to query
gsheets_url = defog.generate_db_schema(tables)
# gsheets_url is a link to a google sheet with the schema of your database
# you can edit the google sheet before uploading the schema to Defog
defog.update_db_schema(gsheets_url)
3. Integrate with your App, or use as a microservice
You can either integrate Defog in your app, or create a separate microservice for Defog
a. Creating a microservice for Defog
Defog is a microservice that can be used to query your database. You can create a microservice for Defog by following the instructions below:
[optional] b. Integrating Defog in your app
Defog can be integrated with your app using the following snippet. Modify it however you want and put it any function!
from defog import Defog
defog = Defog(
api_key = "YOUR_API_KEY",
db_type = "postgres",
db_creds = {
"host": "YOUR_DB_HOST",
"port": YOUR_DB_PORT,
"database": "YOUR_DB_NAME",
"user": "YOUR_DB_USER",
"password": "YOUR_DB_PASS"
}
)
user_question = "how much revenue did I generate this month?"
hard_filters = "only show data for the user with id 123, and no other user"
answer = defog.run_query(user_question, hard_filters=hard_filters)
# answer is a dictionary with the following keys:
# "columns": the columns of the answer. this is a list of strings
# "data": the data of the answer. this is a list of lists
# "generated_query": the query that was generated by Defog
# "is_successful": whether the query was successful or not
4. Making REST API requests from your front-end
You can easily send user queries to Defog from your front-end. This function should make it easy:
const getDefogResults = async(userQuestion) => {
const url = "YOUR_MICROSERVICE_ENDPOINT";
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
question: userQuestion
})
});
const json = await response.json();
return json;
}
5. Visualize and render the query result with our front-end components
If you would like an easy way to visualize query results, use our React front-end components.
<AskDefog
apiEndpoint={"YOUR_API_ENDPOINT"}
showQuery={true}
maxHeight={600}
/>