Building a Notion Connector App with Streamlit

Tired of wrestling with Notion’s API? There’s a simpler way. A few lines of code, one integration token, and you’re connected. Here’s how we built a streamlined app with Streamlit to fetch data from any Notion database.

If you've been looking for a simple way to connect and fetch data from your Notion databases without getting tangled up in complex API calls, our Notion Connector App is exactly what you need as a starting point.

Let’s dive into how we built this simple starter app using Streamlit to connect to any Notion database using your Notion Integration Token and fetch the data from any specified Database ID. This is just the beginning—we’re laying the groundwork for more advanced features that can easily be added later!

🛠️ How Does It Work?

Under the hood, this app leverages the Notion API through the Langchain Community’s NotionDBLoader, which makes it easy to interact with Notion databases. Here’s a quick rundown of what’s happening:

  • Integration Token: The app connects to your Notion account using the integration token you’ve created via Notion's API.
  • Database ID: You can specify the ID of any Notion database you have access to, and the app will fetch its contents.
  • Data Display: The fetched data is displayed in a pandas DataFrame and can be downloaded as a CSV file.

✨ How to Create a Notion Integration and Grant Access to Your Database

Before you can use this app, you need to set up a Notion integration and give it permission to access your database. Follow these simple steps:

1. Create a Notion Integration

To create an integration in Notion:

  • Head to the Notion Developers Portal and click "Create new integration."
  • Give your integration a name and assign it the correct permissions (e.g., read-only or full access).
  • Once your integration is created, you'll receive an Integration Token. This token will be used in the app to connect to your Notion workspace.

More details can be found in the Notion API documentation on authorization.

2. Grant Access to the Notion Database

After creating your integration, you need to connect it to the database you'd like to fetch data from. Here's how to do that:

  • Open the Notion page that contains the database.
  • Click on the three dots in the upper-right corner of the page.
  • Select "Add connections" and search for your newly created integration by name.
  • Once the integration is added, it will have the permissions needed to access the database.

You can find a detailed guide on how to add and manage connections with the API from Notion's Help Center.

What’s Under the Hood?

Let’s take a closer look at how the app is structured.

Setting Up the Streamlit App

First, we set up the Streamlit app with a clean and simple interface. Users input their Notion Integration Token and Database ID to establish a connection.

In this basic version, the Notion Integration Token is set via the sidebar and handled through the session state, ensuring it’s securely stored for the duration of the session. The database id is taken as user input to fetch the data from the desired database.

# Check if the required API key is available
if 'NOTION_TOKEN' not in st.session_state or not st.session_state['NOTION_TOKEN']:
    st.error("Notion integration token is required for this app. Please enter it in the sidebar on the Home page.")
    st.stop()

# API Key and Database ID Input
notion_token = st.session_state['NOTION_TOKEN']
database_id = st.text_input("Enter your Notion Database ID from which you want to pull the data")

Connecting to the Notion Database

When the user hits the "Load Notion Database" button, we use the NotionDBLoader to fetch data from the specified Notion database.

if st.button("Load Notion Database"):
    if not notion_token or not database_id:
        st.error("Please provide both Notion Integration Token and Database ID to continue.")
    else:
        with st.spinner("Loading Notion Database..."):
            try:
                loader = NotionDBLoader(
                    integration_token=os.environ["NOTION_TOKEN"],
                    database_id=os.environ["DATABASE_ID"],
                    request_timeout_sec=30,
                )
                docs = loader.load()
                st.success("Notion Database loaded successfully!")
                st.session_state.notion_df = docs_to_dataframe(docs)
            except Exception as e:
                st.error(f"Error: {str(e)}")

Displaying and Downloading the Data

Once the data is fetched, we display it in a nice table using Streamlit’s dataframe widget. We also offer the option to download the data as a CSV file, which is great for anyone who needs to do further processing or store the data for later.

if st.session_state.notion_df is not None:
    st.subheader("Notion Database Content")
    st.dataframe(st.session_state.notion_df)
    
    csv = st.session_state.notion_df.to_csv(index=False)
    st.download_button(
        label="Download data as CSV",
        data=csv,
        file_name="notion_database.csv",
        mime="text/csv",
    )

✨ Why Is This App Useful?

  • Quick Start with Notion API: This app provides a basic, yet powerful way to connect to a Notion database and pull data without having to manually deal with the API.
  • Extendable: The current version is a foundation—future features like using LLMs to query the data, editing data, more advanced queries, or even pushing data back into Notion can easily be built on top of it.
  • Data on Demand: By letting users download the data as a CSV file, they can quickly transition from fetching data to doing analysis in tools like Excel, Python, or Google Sheets.

💡 How Can We Use This Starter with LLMs?

This starter app isn’t just limited to fetching data from Notion. You can take it further by integrating with a Large Language Model (LLM) like OpenAI’s GPT models to make intelligent queries about the data within your Notion database. Imagine asking a question like “What are the top 5 completed tasks in my project database?” and having the app process that query, fetch the relevant data from Notion, and return a concise, human-readable answer. By combining the data-fetching capabilities of this app with the natural language understanding of an LLM, you can build powerful tools for automating workflows, generating insights, or even summarizing project updates. The integration possibilities are endless—whether it’s for tracking tasks, analyzing project timelines, or generating reports, this Notion Connector provides a great starting point for building a smarter, more dynamic system.

Wrapping It Up

The Notion Connector App is a simple, yet effective way to get started with fetching data from a Notion database. It’s lightweight, extendable, and can be built upon to create more complex functionality as needed. Whether you’re just starting out with Notion’s API or looking for a quick solution to fetch and analyze your data, this app provides a solid foundation to grow from.

Try it out and let us know what you think!



Author

Harshad Suryawanshi

03/10/2024