From f689b3dc39e06aa90629f6ccb00724276ba4f273 Mon Sep 17 00:00:00 2001 From: Tom Gotsman Date: Tue, 7 Apr 2026 09:47:24 -0700 Subject: [PATCH 1/3] no image update --- pcweb/pages/blog/blog.py | 14 ++++++++------ pcweb/pages/blog/page.py | 14 +++++++++----- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/pcweb/pages/blog/blog.py b/pcweb/pages/blog/blog.py index 78b14b811..73ad38539 100644 --- a/pcweb/pages/blog/blog.py +++ b/pcweb/pages/blog/blog.py @@ -102,9 +102,9 @@ def card_inner(meta: dict, path: str) -> rx.Component: rx.el.div( rx.image( src=( - meta["image"] - if meta["image"].startswith(("http://", "https://")) - else f"{REFLEX_ASSETS_CDN}{meta['image'].lstrip('/')}" + meta.get("image", "") + if meta.get("image", "").startswith(("http://", "https://")) + else f"{REFLEX_ASSETS_CDN}{meta.get('image', '').lstrip('/')}" ), loading="eager", custom_attrs={"fetchPriority": "high"}, @@ -112,7 +112,9 @@ def card_inner(meta: dict, path: str) -> rx.Component: class_name="group-hover:scale-105 w-full h-full transition-transform duration-150 ease-out object-top object-cover", ), class_name="relative flex-shrink-0 border-slate-5 border-b border-solid w-full h-[17.5rem] overflow-hidden", - ), + ) + if meta.get("image") + else rx.fragment(), rx.el.div( rx.el.span( meta["title"], @@ -225,11 +227,11 @@ def blogs(): path=route, title=seo_title, description=document.metadata["description"], - image=document.metadata["image"], + image=document.metadata.get("image", ""), meta=create_meta_tags( title=seo_title, description=document.metadata["description"], - image=document.metadata["image"], + image=document.metadata.get("image", ""), url=f"https://reflex.dev{route}", ), )(lambda doc=document, route=route: page(doc, route)) diff --git a/pcweb/pages/blog/page.py b/pcweb/pages/blog/page.py index 8ff812316..0aa9afb6e 100644 --- a/pcweb/pages/blog/page.py +++ b/pcweb/pages/blog/page.py @@ -206,7 +206,7 @@ def page(document, route) -> rx.Component: description=meta["description"], author=meta["author"], date=str(meta["date"]), - image=meta["image"], + image=meta.get("image", ""), url=page_url, faq=meta.get("faq"), author_bio=meta.get("author_bio"), @@ -275,15 +275,19 @@ def page(document, route) -> rx.Component: rx.el.div( rx.image( src=( - meta["image"] - if meta["image"].startswith(("http://", "https://")) - else f"{REFLEX_ASSETS_CDN}{meta['image'].lstrip('/')}" + meta.get("image", "") + if meta.get("image", "").startswith( + ("http://", "https://") + ) + else f"{REFLEX_ASSETS_CDN}{meta.get('image', '').lstrip('/')}" ), alt=f"Image for blog post: {meta['title']}", loading="eager", custom_attrs={"fetchPriority": "high"}, class_name="rounded-xl object-contain w-full h-auto mb-4", - ), + ) + if meta.get("image") + else rx.fragment(), rx.el.div( xd.render(document, document.filename), class_name="flex flex-col gap-4 w-full xl:max-w-[45rem]", From 8037c62cfcd3772eac00445b9a67cfd102c84092 Mon Sep 17 00:00:00 2001 From: Tom Gotsman Date: Tue, 7 Apr 2026 09:50:21 -0700 Subject: [PATCH 2/3] new 40 blogs --- blog/build-dashboard-google-auth.md | 149 ++++++++++++++ blog/build-dashboard-intercom.md | 157 +++++++++++++++ blog/build-dashboard-mongodb.md | 146 ++++++++++++++ blog/build-dashboard-openai.md | 155 +++++++++++++++ blog/build-dashboard-resend-python.md | 143 ++++++++++++++ blog/build-dashboard-salesforce.md | 153 +++++++++++++++ blog/build-dashboard-servicenow.md | 164 ++++++++++++++++ blog/build-dashboard-twilio-python.md | 152 +++++++++++++++ blog/build-dashboard-with-anthropic.md | 139 ++++++++++++++ blog/build-dashboard-with-auth0.md | 167 ++++++++++++++++ blog/build-dashboard-with-database.md | 161 ++++++++++++++++ blog/build-dashboard-with-gemini.md | 142 ++++++++++++++ blog/build-dashboard-with-groq.md | 139 ++++++++++++++ blog/build-dashboard-with-postgresql.md | 143 ++++++++++++++ blog/build-dashboard-with-slack.md | 162 ++++++++++++++++ blog/build-fhir-api-dashboard-python.md | 162 ++++++++++++++++ blog/build-python-web-app-aws-s3.md | 160 ++++++++++++++++ blog/build-python-web-app-hubspot.md | 154 +++++++++++++++ blog/build-python-web-app-hugging-face.md | 151 +++++++++++++++ blog/build-python-web-app-mssql.md | 141 ++++++++++++++ blog/build-python-web-app-okta-auth.md | 153 +++++++++++++++ blog/build-python-web-app-ollama.md | 152 +++++++++++++++ blog/build-python-web-app-with-notion.md | 159 +++++++++++++++ blog/build-python-web-app-with-stripe.md | 144 ++++++++++++++ blog/build-python-web-app-with-zendesk.md | 147 ++++++++++++++ blog/how-to-build-dashboard-with-github.md | 156 +++++++++++++++ blog/how-to-build-dashboard-with-mysql.md | 181 ++++++++++++++++++ blog/how-to-build-dashboard-with-plaid.md | 143 ++++++++++++++ blog/how-to-build-dashboard-with-snowflake.md | 142 ++++++++++++++ ...w-to-build-python-web-app-with-bigquery.md | 127 ++++++++++++ ...w-to-build-python-web-app-with-dynamodb.md | 157 +++++++++++++++ blog/how-to-build-python-web-app-with-gcp.md | 146 ++++++++++++++ blog/how-to-build-python-web-app-with-jira.md | 147 ++++++++++++++ ...-to-build-python-web-app-with-langchain.md | 159 +++++++++++++++ ...how-to-build-python-web-app-with-linear.md | 146 ++++++++++++++ ...w-to-build-python-web-app-with-supabase.md | 154 +++++++++++++++ ...n-web-app-azure-auth-microsoft-entra-id.md | 160 ++++++++++++++++ blog/python-web-app-databricks.md | 157 +++++++++++++++ blog/python-web-app-epic-ehr.md | 156 +++++++++++++++ blog/python-web-app-with-perplexity.md | 139 ++++++++++++++ 40 files changed, 6065 insertions(+) create mode 100644 blog/build-dashboard-google-auth.md create mode 100644 blog/build-dashboard-intercom.md create mode 100644 blog/build-dashboard-mongodb.md create mode 100644 blog/build-dashboard-openai.md create mode 100644 blog/build-dashboard-resend-python.md create mode 100644 blog/build-dashboard-salesforce.md create mode 100644 blog/build-dashboard-servicenow.md create mode 100644 blog/build-dashboard-twilio-python.md create mode 100644 blog/build-dashboard-with-anthropic.md create mode 100644 blog/build-dashboard-with-auth0.md create mode 100644 blog/build-dashboard-with-database.md create mode 100644 blog/build-dashboard-with-gemini.md create mode 100644 blog/build-dashboard-with-groq.md create mode 100644 blog/build-dashboard-with-postgresql.md create mode 100644 blog/build-dashboard-with-slack.md create mode 100644 blog/build-fhir-api-dashboard-python.md create mode 100644 blog/build-python-web-app-aws-s3.md create mode 100644 blog/build-python-web-app-hubspot.md create mode 100644 blog/build-python-web-app-hugging-face.md create mode 100644 blog/build-python-web-app-mssql.md create mode 100644 blog/build-python-web-app-okta-auth.md create mode 100644 blog/build-python-web-app-ollama.md create mode 100644 blog/build-python-web-app-with-notion.md create mode 100644 blog/build-python-web-app-with-stripe.md create mode 100644 blog/build-python-web-app-with-zendesk.md create mode 100644 blog/how-to-build-dashboard-with-github.md create mode 100644 blog/how-to-build-dashboard-with-mysql.md create mode 100644 blog/how-to-build-dashboard-with-plaid.md create mode 100644 blog/how-to-build-dashboard-with-snowflake.md create mode 100644 blog/how-to-build-python-web-app-with-bigquery.md create mode 100644 blog/how-to-build-python-web-app-with-dynamodb.md create mode 100644 blog/how-to-build-python-web-app-with-gcp.md create mode 100644 blog/how-to-build-python-web-app-with-jira.md create mode 100644 blog/how-to-build-python-web-app-with-langchain.md create mode 100644 blog/how-to-build-python-web-app-with-linear.md create mode 100644 blog/how-to-build-python-web-app-with-supabase.md create mode 100644 blog/python-web-app-azure-auth-microsoft-entra-id.md create mode 100644 blog/python-web-app-databricks.md create mode 100644 blog/python-web-app-epic-ehr.md create mode 100644 blog/python-web-app-with-perplexity.md diff --git a/blog/build-dashboard-google-auth.md b/blog/build-dashboard-google-auth.md new file mode 100644 index 000000000..b5f28076a --- /dev/null +++ b/blog/build-dashboard-google-auth.md @@ -0,0 +1,149 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Google Auth in 2026" +title_tag: "Build Dashboard With Google Auth 2026" +description: "Learn how to build a dashboard with Google Auth in April 2026. Step-by-step guide covering OAuth setup, session handling, and deployment in Python." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Google Auth dashboard Python, Google OAuth dashboard, SSO dashboard Python, Google login dashboard, auth analytics" + } +] +faq: [ + {"question": "Can I build a dashboard with Google Auth without JavaScript?", "answer": "Yes. Reflex lets you build the entire Google OAuth flow, session handling, and dashboard UI in pure Python without writing any JavaScript. Your authentication state, event handlers, and UI components all live in the same Python file."}, + {"question": "Google Auth dashboard Reflex vs Streamlit?", "answer": "Reflex handles OAuth callbacks and session state server-side with event-based architecture, while Streamlit's script rerun model makes multi-step auth flows unreliable. Reflex also gives you full CSS control and 60+ components for production dashboards, whereas Streamlit locks you into basic layouts with limited customization."}, + {"question": "How do I set up Google Auth in a Reflex project?", "answer": "Create OAuth credentials in Google Cloud Console's Auth Platform section, then configure them once at the project level in Reflex. Every app within that project automatically inherits the Google Auth setup without requiring separate OAuth wiring per dashboard."}, + {"question": "What user data does Google OAuth return for dashboards?", "answer": "Google returns email, full name, profile photo URL, locale, verified status, and a unique identifier in the `sub` field. For Google Workspace users, you also get the `hd` claim showing domain affiliation, which you can use for role-based access control."}, + {"question": "When should I self-host vs deploy to Reflex Cloud?", "answer": "Self-host when you need OAuth tokens to stay within your own network for compliance reasons, or when regulated industries require specific data sovereignty controls. Use Reflex Cloud for faster deployment with built-in CI/CD, multi-region scaling, and OpenTelemetry tracing without managing infrastructure yourself."}, + {"question": "Can I use Google Auth with role-based access control in Reflex?", "answer": "Yes. Google Workspace returns the `hd` claim showing domain affiliation, which you can use to implement role-based access control. You define permission logic directly in your Python state class, determining what each user can see based on their email domain or other profile data."}, + {"question": "How does Reflex handle OAuth token storage in production?", "answer": "Reflex stores OAuth tokens server-side, never exposing them to the browser. This backend-first architecture keeps secrets secure and makes Reflex suitable for regulated industries where token storage location affects audit outcomes."}, + {"question": "What components does Reflex provide for building Google Auth dashboards?", "answer": "Reflex includes 60+ built-in components covering stat cards, avatars, badges, data tables, navigation menus, and modal dialogs. These components handle everything from single-profile views to multi-user admin panels, and you can also wrap any React component directly in Python when you need custom functionality."}, + {"question": "How does project-level auth configuration work in Reflex?", "answer": "You configure Google Auth credentials once at the project level in Reflex, and every app within that project automatically inherits the setup. This means building multiple dashboards under the same project requires no separate OAuth wiring for each one."}, + {"question": "Can I track user activity with Google Auth in Reflex?", "answer": "Yes. You can build a team activity tracker that ties actions and events to specific authenticated identities from Google OAuth. This gives you a clear audit trail tied to real Google accounts, with user profile data like email and name automatically associated with each event."}, + {"question": "What's the difference between Reflex and code-generation tools like Lovable or Bolt for auth?", "answer": "Reflex configures authentication once at the project level and shares it across all apps, while code-generation tools produce standalone artifacts that each require separate OAuth setup. Reflex also keeps your entire auth flow in readable Python code rather than generated JavaScript."}, + {"question": "How do I monitor authentication failures in production?", "answer": "Reflex supports OpenTelemetry tracing to monitor OAuth error rates and session patterns in production. This helps catch token refresh failures or unexpected sign-out loops before users report them, which is critical since auth-related bugs are harder to reproduce than most application errors."}, + {"question": "Can I automatically populate user profiles from Google Auth data?", "answer": "Yes. Google OAuth returns profile data including name, email, photo URL, and locale on first login. You can build an onboarding hub that auto-populates user details from these Google profile claims, removing manual data entry entirely."}, + {"question": "Does Reflex require a separate frontend build for Google Auth dashboards?", "answer": "No. Reflex ships your OAuth logic, session state, and UI components together in one deployment step without a separate frontend build. Your entire authentication flow and dashboard UI live in the same Python codebase."}, + {"question": "How do I handle Google Workspace domain filtering in a dashboard?", "answer": "For Google Workspace users, OAuth returns the `hd` claim showing domain affiliation. You can use table components with filter inputs scoped to domain or organizational unit, and WebSocket-based state sync keeps those filtered lists current without manual refresh."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Build authenticated dashboards in pure Python with Google OAuth handling identity, sessions, and profile data without JavaScript + +- Reflex configures Google Auth once at project level and shares it across all apps, eliminating repeated OAuth setup + +- Deploy dashboards with tokens stored server-side for compliance, plus OpenTelemetry tracing to catch auth failures in production + +- Reflex outputs Python code for Google Auth dashboards, making them readable and debuggable by Python developers without frontend expertise + +## What You Can Build: Google Auth Dashboard Overview + +When a user signs in with Google OAuth, you get more than just a login event. Google returns the user's name, email, profile photo URL, locale, and a unique identifier in the `sub` key. That profile data becomes the foundation for a whole category of internal tools. + +Here's what you can realistically build with a Google Auth dashboard in Reflex: + +- A user management panel that displays authenticated team members, their Google profile photos, and domain affiliations so admins can audit access at a glance. + +- An [internal admin tool](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) with role-based access, where Google Workspace email domains determine what each user can see across different sections of the app. + +- A team activity tracker that ties actions and events to specific authenticated identities, giving you a clear audit trail tied to real Google accounts. + +- An onboarding hub that auto-populates user details from Google profile claims on first login, removing manual data entry entirely. + +The key distinction here is that this is an authentication-first dashboard. Google OAuth handles the identity layer, and your application surfaces that identity across pages, permissions, and activity logs. You are not pulling analytics from Google APIs. You are using Google as the front door. + +What makes Reflex a natural fit is that authentication integrations are configured once at the project level and shared across every app within that project. Set up Google Auth once, and every dashboard you build inherits it automatically. + +## Why Python Developers Choose Reflex for Google Auth Dashboards + +Building an authenticated dashboard usually means splitting your work across two codebases: a Python backend handling OAuth callbacks and session logic, and a JavaScript frontend building the actual UI. For most Python teams, that split is where projects stall. + +Reflex removes it entirely. Google Auth setup, session state, event handlers, and every UI component live in the same Python file. There is no context-switching between languages, no separate build pipeline to coordinate, and no JavaScript runtime to debug when a token refresh silently fails. + +The project-level integration configuration is worth calling out. Google Auth credentials are registered once at the project level and inherited by every app in that project. If you're building a user management panel, an admin tool, and an onboarding hub under the same project, none of them require a separate OAuth setup. Compare that to a code-generation tool like Lovable or Bolt, where each generated app is effectively a standalone artifact with its own auth wiring. + +On the component side, Reflex's 60+ built-in components cover everything a Google Auth dashboard needs: avatars, data tables, navigation menus, and modal dialogs. When you need something more custom, you can wrap any React component directly in Python. The [template gallery](https://reflex.dev/templates/) also gives you production-ready dashboard scaffolding to start from instead of building from scratch. + +## Connecting Google Auth to Your Reflex App + +Google's OAuth implementation runs on [OAuth 2.0 and OpenID Connect](https://developers.google.com/identity/openid-connect/openid-connect). Google recently consolidated its setup into a dedicated [Google Auth section](https://developers.googleblog.com/usability-and-safety-updates-to-google-auth-platform/) in Google Cloud Console. You'll create credentials there, grab your client ID and secret, and register your redirect URI before touching any application code. + +From there, Reflex's state management system handles everything on the Python side. Because Reflex's backend is a Python class, you define your authentication state (user profile, token status, session data) directly in that class. Any Python OAuth library from PyPI installs and integrates without middleware layers or custom API gateways, similar to how [Microsoft Azure Auth](https://reflex.dev/blog/microsoft-azure-authentication/) works in Reflex. + +### Authentication Flow Mechanics + +The flow itself is straightforward. A user clicks your login button, Reflex redirects them to Google's authorization endpoint, and Google sends an authorization code back to your registered callback URL through the [Sign In with Google](https://reflex.dev/blog/implementing-sign-in-with-google/) flow. A Reflex event handler then intercepts that code, exchanges it for access tokens on the server, and stores the returned profile data in your application state. + +That backend-first model matters for security. OAuth secrets never touch the browser. Tokens live server-side, and your UI simply reacts to state changes that the event handler triggers after a successful exchange. This architecture also scales cleanly: adding role-based access or session expiration logic means updating your Python state class, with no frontend rewiring required. + +## Key Dashboard Components for Google Auth Data + +Google Auth returns a structured JSON payload from its userinfo endpoint, so the component choices practically write themselves. Here's how that data maps to a component library like Reflex's: + +| User Data Field | Source | Component Type | Use Case | +|---|---|---|---| +| Email | OAuth userinfo endpoint | Text or Badge | Primary identifier | +| Full name | OAuth userinfo endpoint | Heading or Stat | Profile display | +| Profile picture | OAuth userinfo endpoint | Image or Avatar | Visual identification | +| Verified status | OAuth userinfo endpoint | Badge | Trust indicator | +| Domain affiliation | OAuth userinfo `hd` claim | Text | Workspace filtering | + +### User Profile Display Components + +Stat cards, avatar components, and badge elements cover the core profile UI. Computed vars pull directly from OAuth state, so the display always reflects the current session without extra fetching logic. + +### Access Control and Team Management UI + +For team directories and admin panels, a table component displays user lists with filter inputs scoped to domain or organizational unit, as seen in the [Admin Console Dashboard](https://reflex.dev/templates/admin-console-dashboard/) template. WebSocket-based state sync keeps those lists current without manual refresh, which matters when access changes need to reflect immediately across active sessions. + +### Dashboard Layout Patterns + +The box layout component handles both single-profile views and multi-user admin panels with equal ease. Common admin dashboards surface email aliases, creation dates, login history, and organizational unit membership. Whether you're building a lightweight profile card or a full user management panel, you compose the same components with different data inputs. + +## Deploying Your Google Auth Dashboard to Production + +Getting your dashboard live involves a few key decisions around hosting, compliance, and observability. + +Reflex's deployment model keeps things straightforward: your OAuth logic, session state, and UI components ship together in one step with [Reflex hosting](https://reflex.dev/hosting/), with no separate frontend build or callback URL reconfiguration required. + +For teams with stricter data requirements, [self-hosting with Docker](https://reflex.dev/blog/self-hosting-reflex-with-docker/) keeps tokens entirely within your own network. This matters in industries with compliance requirements where token storage location affects audit outcomes. Beyond basic deployment, there are a few production concerns worth planning for early: + +- Multi-region deployment reduces global latency for dashboards with international users, and Reflex's architecture supports this without requiring separate configuration per region. For maximum security, consider [on-premises deployment](https://reflex.dev/blog/on-premises-deployment/) to keep all infrastructure inside your company network. + +- CI/CD integration with GitHub Actions lets you automate rollouts whenever auth logic changes, so updates to scopes, session handling, or user roles deploy consistently across environments. + +- OpenTelemetry tracing gives you visibility into OAuth error rates and session patterns in production, which helps catch token refresh failures or unexpected sign-out loops before users report them. + +These aren't afterthoughts. Auth-related bugs in production are harder to reproduce and debug than most application errors, so building in tracing from day one pays off quickly. A well-instrumented deployment will surface whether your Google OAuth flow is succeeding at the rates you expect and flag anomalies as your user base grows. + +## FAQ + +### Can I build a dashboard with Google Auth without JavaScript? + +Yes. Reflex lets you build the entire Google OAuth flow, session handling, and dashboard UI in pure Python without writing any JavaScript. Your authentication state, event handlers, and UI components all live in the same Python file. + +### Google Auth dashboard Reflex vs Streamlit? + +Reflex handles OAuth callbacks and session state server-side with event-based architecture, while Streamlit's script rerun model makes multi-step auth flows unreliable. Reflex also gives you full CSS control and 60+ components for production dashboards, whereas Streamlit locks you into basic layouts with limited customization. + +### How do I set up Google Auth in a Reflex project? + +Create OAuth credentials in Google Cloud Console's Auth section, then configure them once at the project level in Reflex. Every app within that project automatically inherits the Google Auth setup without requiring separate OAuth wiring per dashboard. + +### What user data does Google OAuth return for dashboards? + +Google returns email, full name, profile photo URL, locale, verified status, and a unique identifier in the `sub` field. For Google Workspace users, you also get the `hd` claim showing domain affiliation, which you can use for role-based access control. + +### When should I self-host vs deploy to Reflex Cloud? + +Self-host when you need OAuth tokens to stay within your own network for compliance reasons, or when industries with compliance requirements need specific data sovereignty controls. Use Reflex Cloud for faster deployment with built-in CI/CD, multi-region scaling, and OpenTelemetry tracing without managing infrastructure yourself. diff --git a/blog/build-dashboard-intercom.md b/blog/build-dashboard-intercom.md new file mode 100644 index 000000000..f3902cb03 --- /dev/null +++ b/blog/build-dashboard-intercom.md @@ -0,0 +1,157 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Intercom in 2026" +title_tag: "Build Intercom Dashboard 2026" +description: "Learn how to build custom Intercom dashboards in Python for April 2026. Pull conversation metrics, team data, and AI agent activity into views you control." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Intercom dashboard Python, Intercom API dashboard, customer support dashboard, Intercom metrics, messaging analytics Python" + } +] +faq: [ + {"question": "Can I build an Intercom dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full Intercom dashboards in pure Python, handling both the API integration and the UI without writing any JavaScript. The python-intercom library works directly inside Reflex event handlers and state management."}, + {"question": "Intercom dashboard Streamlit vs Reflex?", "answer": "Streamlit reruns your entire script on every interaction and lacks built-in auth, making it unsuitable for production dashboards with role-based access. Reflex uses event-based updates and ships with authentication out of the box, so leadership and support teams can access different views of the same Intercom data securely."}, + {"question": "How do I handle Intercom's API rate limits when calculating trends?", "answer": "Use Reflex's background jobs to cache aggregated metrics in your database on a schedule, then read from local storage when rendering charts. This avoids hitting the Intercom API 70+ times per dashboard load when calculating monthly satisfaction trends or team performance buckets."}, + {"question": "What's the fastest way to deploy an Intercom dashboard in 2026?", "answer": "Run `reflex deploy` to push your entire app to production in one command. Reflex Cloud handles SSL, multi-region scaling, and infrastructure automatically, with VPC deployment options if you're connecting Intercom data to internal CRM systems or customer health scores."}, + {"question": "When should I build a custom Intercom dashboard instead of using native reporting?", "answer": "When you need to combine Intercom conversation data with CRM metrics, product usage analytics, or internal KPIs in a single view. Native Intercom reporting covers basic team performance and ticket volume well, but custom dashboards let you merge support data with any other system your business tracks."}, + {"question": "How does Reflex handle authentication for Intercom dashboards with multiple user roles?", "answer": "Reflex ships with built-in authentication and access control out of the box, allowing you to create role-based access so leadership and support leads can see different views of the same Intercom data. This eliminates the need for third-party auth setup that other frameworks like Streamlit require."}, + {"question": "Can I combine Intercom data with my CRM or product analytics in one dashboard?", "answer": "Yes. Custom Python dashboards built with Reflex let you pull Intercom conversation data alongside any other system your business tracks, including CRM metrics, internal KPIs, and product usage analytics in a single unified view."}, + {"question": "What Intercom metrics can I track in a custom dashboard?", "answer": "Common metrics include conversation volume trends, first response time, resolution rates, team performance over rolling time windows, Fin AI agent usage patterns and handoff rates, CSAT scores segmented by team or channel, and customer engagement trends across conversations and users."}, + {"question": "Does Reflex support async API calls to Intercom?", "answer": "Yes. Reflex's async event handlers work naturally with the python-intercom library's async client support, allowing you to fire multiple API requests concurrently without blocking the UI, which keeps load times low as your Intercom workspace scales."}, + {"question": "How do I cache Intercom data to improve dashboard performance?", "answer": "Use Reflex's background jobs to fetch and aggregate Intercom metrics on a schedule, storing results in your database. The dashboard then reads from fast local storage instead of hitting the API on every page load, avoiding rate limits and improving response times."}, + {"question": "Can I self-host my Intercom dashboard inside my own network?", "answer": "Yes. Reflex supports VPC deployment and Docker-based self-hosting, keeping your dashboard inside your network perimeter while still accessing Intercom's cloud API over authenticated HTTPS. This is useful when connecting Intercom to proprietary CRM data or internal customer health scores."}, + {"question": "What monitoring tools are available for production Intercom dashboards?", "answer": "Reflex Cloud includes built-in OpenTelemetry integration and ClickHouse log aggregation that track Intercom API latency, rate limit patterns, query performance, and background job health without requiring custom instrumentation."}, + {"question": "How does Reflex's state management work with real-time Intercom data?", "answer": "When users interact with filters or date ranges, Reflex event handlers update the State class, re-query the Intercom API, and push fresh results to the UI via WebSocket automatically. This happens without page reloads or URL changes, keeping the experience responsive."}, + {"question": "What's included in Reflex's built-in dashboard components?", "answer": "Reflex provides 60+ components including DataTables for paginated conversation lists, stat cards for aggregated metrics like CSAT scores, line and bar charts for trend visualization, and dropdown filters for team segmentation—all without requiring custom JavaScript rendering logic."}, + {"question": "How do I set up CI/CD for automated Intercom dashboard deployments?", "answer": "Reflex dashboards integrate with GitHub Actions or GitLab CI to automatically deploy updated logic on merge. Teams running Kubernetes can use Helm chart orchestration, and the entire app packages in a single deployment without coordinating separate frontend and backend pipelines."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build Intercom dashboards in pure Python without JavaScript using Reflex's framework + +- Pull conversation metrics, team performance data, and AI agent activity into custom views you control + +- Background jobs cache aggregated data locally to avoid API rate limits during high-volume queries + +- Reflex handles production deployment with built-in auth, VPC options, and OpenTelemetry observability + +- Reflex is an open-source Python framework that outputs maintainable code teams can debug and extend + +## What You Can Build: Intercom Dashboard Overview + +Intercom's native reporting gets you started, but it has a ceiling. Support teams use it to [track ticket volume and conversation ratings](https://community.intercom.com/api-webhooks-23/intercom-api-for-reporting-11173), and [Intercom's 12 built-in dashboard templates](https://reply.io/blog/intercom-ai-review/) cover team performance, Fin AI Agent activity, response times, and customer satisfaction reasonably well. But what happens when you need to combine that data with your CRM, internal KPIs, or product usage metrics in a [single view](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/)? That's where native tooling falls short. + +Building a custom Python dashboard lets you pull Intercom conversation data alongside anything else your business tracks. Customer success managers get visibility into engagement trends across conversations, users, and teams. Operations leads can monitor AI copilot adoption patterns alongside staffing data. Leadership gets a single read-only view that surfaces aggregated satisfaction scores and team performance over time, without bouncing between tools. + +The most common dashboards teams build fall into a few categories: + +- Conversation analytics: volume trends, first response time, and resolution rates pulled directly from the Intercom API into charts your team actually owns. + +- Team performance: individual and group metrics calculated over rolling time windows, not limited to Intercom's fixed reporting periods. + +- AI agent activity: Fin usage patterns, handoff rates, and deflection percentages surfaced alongside human agent workload. + +- Customer satisfaction: CSAT trends segmented by team, channel, or product area, merged with data from your CRM or product analytics. + +Reflex handles all of this in pure Python, with no JavaScript required. + +## Why Python Developers Choose Reflex for Intercom Dashboards + +Python teams working with Intercom data typically hit a wall: the API logic lives in Python, but displaying it requires a separate JavaScript frontend. Reflex removes that split entirely. The same developer who writes the Intercom API calls also builds the UI, manages state, and handles data transformations, all without switching languages or codebases. + +The [python-intercom library](https://github.com/intercom/python-intercom) installs via pip and drops directly into Reflex event handlers and background jobs. No glue code, no adapter layers. When a user filters by date range or team, the event handler fetches fresh Intercom data and updates the UI automatically through Reflex's state management system. + +Reflex's [60+ built-in components](https://reflex.dev/blog/custom-components/) cover the full dashboard surface: tables for conversation logs, line charts for volume trends, stat cards for CSAT scores, and dropdown filters for team segmentation. These map naturally to Intercom's data shapes without custom display logic. + +### Why [Reflex Pulls Ahead of Streamlit](https://reflex.dev/blog/reflex-streamlit/) in Production + +The gap becomes obvious once real traffic hits. Consider how the two frameworks compare on the factors that matter most for a customer support dashboard: + +| Factor | Streamlit | Reflex | +|---|---|---| +| Execution model | Full script reruns on every interaction | Event-based, only relevant state updates | +| Auth and access control | Requires third-party setup | Built in out of the box | +| Data volume scaling | Memory leaks appear as volumes grow | Handles growing datasets without full reruns | +| Language requirement | Python only | Python for UI, state, and API logic | + +When leadership and support leads need different views of the same data, role-based access control stops being optional. Reflex ships with it by default. + +## Connecting Intercom to Your Reflex App + +Intercom's [REST API](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis) lets you retrieve and update account data or wire Intercom directly into your own product. Getting that connection running inside Reflex takes three steps: install the SDK, initialize the client, and store your credentials safely. + +The [Python library](https://pypi.org/project/python-intercom/) installs via pip into your virtual environment, then the client lives inside your Reflex State class. Your access token stays in an environment variable, so it never touches the frontend. Because Reflex's backend architecture accesses secrets directly server-side, credentials for sensitive customer data or internal CRM systems stay contained. + +Reflex's project-level integration configuration means you authenticate with Intercom once and reference that credential across every event handler, background job, and computed var in your app. No re-initializing per page, no copy-pasted config blocks. + +### Async Support Out of the Box + +The Python library supports async clients, which pair naturally with Reflex's [async event handlers](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/). When a support lead filters by date range, the handler calls the Intercom API without blocking the rest of the UI. For teams running self-hosted deployments, those async calls work identically in both local and production environments. + +This matters at scale. A dashboard pulling conversation counts, contact activity, and ticket status simultaneously can fire those requests concurrently, keeping load times low even as your Intercom workspace grows. + +## Key Dashboard Components for Intercom Data + +Intercom's API surfaces rich data, but that data needs the right components to become useful. Here's how Reflex's built-in components map to each layer of a support dashboard. + +### Conversation Metrics and Tables + +Reflex's [DataTable component](https://reflex.dev/blog/using-table-component/) handles paginated conversation lists natively, letting users filter by assignee, status, or tag without JavaScript. Stat cards sit alongside the table to display aggregated counts like open conversations, average first response time, and CSAT scores, calculated as computed vars directly in your State class. + +### Time Series Charts for Support Trends + +Building a 12-month satisfaction trend from Intercom's search API can require 70+ API calls per render when calculating averages for each rating value per monthly bucket. That's a real rate limit problem. Reflex's background jobs let you cache aggregated metrics in your database and refresh on a schedule, so the dashboard reads from fast local storage instead of hammering the API on every load. Reflex's chart components then visualize those cached results reactively whenever state updates. + +### Real-Time Filters and Search + +Event handlers make filtering clean. A user picks a date range or team member, the handler updates State, re-queries Intercom, and pushes results via WebSocket. No page reload, no URL juggling. + +| Dashboard Component | Intercom Data Type | Reflex Component | Update Pattern | +|---|---|---|---| +| Conversation list | Conversations API | DataTable | Event handler + pagination | +| Team performance | Teammates + Conversations | BarChart | Computed var aggregation | +| Satisfaction trends | Conversation ratings | LineChart | Background job cache | +| Active tickets count | Search API total_count | StatCard | Real-time WebSocket push | + +## Deploying Your Intercom Dashboard to Production + +Getting your dashboard from local to live is straightforward. A single deploy command packages your entire app, including Intercom API logic, cached metrics models, and auth configuration, without coordinating separate frontend and backend pipelines. [Reflex Cloud](https://reflex.dev/hosting/) handles SSL, multi-region scaling, and infrastructure automatically. See the deploy quick start for the full walkthrough. + +For teams connecting Intercom to proprietary CRM data or internal customer health scores, [VPC deployment](https://reflex.dev/blog/self-hosting-reflex-with-docker/) keeps the dashboard inside your network perimeter while Intercom's cloud API remains accessible over authenticated HTTPS. Nothing sensitive leaves your environment. + +CI/CD fits naturally into this workflow. GitHub Actions or GitLab CI deploys updated dashboard logic automatically on merge, and Helm chart orchestration supports teams running Kubernetes-native infrastructure. The [templates gallery](https://reflex.dev/templates/) includes starting points for dashboard patterns you can fork and extend without rebuilding from scratch. + +Production observability comes built in. Reflex Cloud's OpenTelemetry integration and ClickHouse log aggregation cover Intercom API latency, rate limit patterns, and query performance across your database layer without custom instrumentation. If a background job stalls or a computed var runs slow under load, you'll catch it before your support team does. + +## FAQ + +### Can I build an Intercom dashboard without JavaScript? + +Yes. Reflex lets you build full Intercom dashboards in pure Python, handling both the API integration and the UI without writing any JavaScript. The python-intercom library works directly inside Reflex event handlers and state management. + +### Intercom dashboard Streamlit vs Reflex? + +Streamlit reruns your entire script on every interaction and lacks built-in auth, making it unsuitable for production dashboards with role-based access. Reflex uses event-based updates and ships with authentication out of the box, so leadership and support teams can access different views of the same Intercom data securely. + +### How do I handle Intercom's API rate limits when calculating trends? + +Use Reflex's background jobs to cache aggregated metrics in your database on a schedule, then read from local storage when drawing charts. This avoids hitting the Intercom API 70+ times per dashboard load when calculating monthly satisfaction trends or team performance buckets. + +### What's the fastest way to deploy an Intercom dashboard in 2026? + +Run `reflex deploy` to push your entire app to production in one command. Reflex Cloud handles SSL, multi-region scaling, and infrastructure automatically, with VPC deployment options if you're connecting Intercom data to internal CRM systems or customer health scores. + +### When should I build a custom Intercom dashboard instead of using native reporting? + +When you need to combine Intercom conversation data with CRM metrics, product usage analytics, or internal KPIs in a single view. Native Intercom reporting covers basic team performance and ticket volume well, but custom dashboards let you merge support data with any other system your business tracks. diff --git a/blog/build-dashboard-mongodb.md b/blog/build-dashboard-mongodb.md new file mode 100644 index 000000000..bc9b9b559 --- /dev/null +++ b/blog/build-dashboard-mongodb.md @@ -0,0 +1,146 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With MongoDB in 2026" +title_tag: "Build MongoDB Dashboard 2026" +description: "Learn to build MongoDB dashboards in pure Python with real-time analytics, PyMongo integration, and production deployment in April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "MongoDB dashboard Python, MongoDB analytics, PyMongo dashboard, NoSQL dashboard, MongoDB metrics Python, database monitoring" + } +] +faq: [ + {"question": "Can I build a MongoDB dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full MongoDB dashboards in pure Python, using PyMongo queries directly in your backend event handlers without writing any JavaScript."}, + {"question": "MongoDB Charts vs Reflex for building dashboards?", "answer": "MongoDB Charts works well for basic analytics with zero code, but Reflex gives you full control to add authentication, custom business logic, multi-page navigation, and complex workflows that Charts cannot handle. If you need more than simple visualizations, Reflex is the better choice."}, + {"question": "How do I handle nested MongoDB documents in dashboard tables?", "answer": "Use expandable tables for nested arrays and objects, or flatten data selectively at the state layer with default values for missing fields. This prevents render errors when documents have inconsistent schemas while preserving the hierarchical structure where it matters."}, + {"question": "What's the fastest way to connect PyMongo to a Reflex dashboard?", "answer": "Install `pymongo` via pip and write connection logic directly in your Reflex state classes using your MongoDB connection string. Reflex stores integration credentials at the project level, so multiple dashboards automatically inherit the same Atlas cluster connection without reconfiguring each app."}, + {"question": "When should I use computed vars for MongoDB aggregation results?", "answer": "Use computed vars when your aggregation pipeline results derive from state variables that change based on user interactions. The UI updates automatically when state changes, giving you real-time dashboard updates without manual polling or refresh triggers."}, + {"question": "How does Reflex handle real-time updates for MongoDB dashboards?", "answer": "Reflex uses WebSocket state synchronization to automatically update the UI when backend state changes. When your PyMongo queries complete or aggregation results update, the browser reflects the new data immediately without polling or manual refresh triggers."}, + {"question": "Can I connect Reflex to a self-hosted MongoDB instance or only Atlas?", "answer": "Reflex works with both MongoDB Atlas cloud clusters and self-hosted MongoDB instances, including local development environments and replica sets. The connection pattern is the same across all deployment types, with only the connection string changing."}, + {"question": "What happens when my MongoDB documents have different fields across the collection?", "answer": "Define default values at the state layer before data reaches your components, ensuring every chart or table receives a predictable structure. This prevents render errors when documents have inconsistent schemas while maintaining flexibility for variable fields."}, + {"question": "How does Reflex reduce latency when querying MongoDB?", "answer": "Reflex's multi-region deployment lets you place your dashboard application close to your Atlas cluster, reducing round-trip time on aggregation queries. This is especially important for dashboards running heavy pipeline operations or processing time-series data."}, + {"question": "Do I need to set up a separate API server to connect MongoDB to my dashboard?", "answer": "No. PyMongo calls run directly inside Reflex state classes and event handlers on the backend, with no middleware layer, REST proxy, or separate server needed to bridge your database to your frontend."}, + {"question": "Can I add authentication and user permissions to a MongoDB dashboard built with Reflex?", "answer": "Yes. Unlike MongoDB Charts which has limited customization, Reflex dashboards support full authentication flows, user permissions, and custom business logic, allowing you to control who can see which pages and data."}, + {"question": "How do I visualize MongoDB aggregation pipeline results in a dashboard?", "answer": "Use bar or pie charts for results from $group and $facet stages, or line charts for time-series aggregations. Run your aggregation pipeline in backend event handlers as regular Python functions, and the results automatically feed into chart components through state updates."}, + {"question": "What components work best for displaying MongoDB time-series collections?", "answer": "Line charts are ideal for time-series data where documents arrive continuously and you need to visualize trends across configurable time windows. Stat cards complement these by showing real-time metrics like insert rates and document counts."}, + {"question": "How does deploying a Reflex MongoDB dashboard differ from deploying a traditional web app?", "answer": "Reflex packages your PyMongo connection logic, query code, and UI into a single deployable unit with one command. There's no separate frontend build step or independent API server configuration needed."}, + {"question": "Can I build multiple MongoDB dashboards that share the same database connection?", "answer": "Yes. Reflex stores integration credentials at the project level, so all applications in a project automatically inherit the same MongoDB connection configuration without copy-pasting secrets or reconfiguring each individual app."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build MongoDB dashboards in pure Python using Reflex, querying collections with PyMongo directly in your backend without translation layers or separate API servers. + +- Reflex handles nested MongoDB documents and variable schemas through expandable tables, stat cards, and chart components that update in real-time via WebSocket state sync. + +- MongoDB integration credentials configure once at the project level and automatically share across all apps, eliminating per-app reconfiguration. + +- Deploy your dashboard with one command to multi-region infrastructure that places your app close to your Atlas cluster, cutting query latency. + +- Reflex is a Python framework that builds production-grade web apps entirely in Python, with 28,000+ GitHub stars and use by 40% of Fortune 500 companies. + +## What You Can Build: MongoDB Dashboard Overview + +MongoDB's document model stores data in nested JSON-like structures, with collections full of arrays, embedded objects, and variable fields that don't fit neatly into rows and columns. Building a dashboard on top of that requires a different approach than querying a relational table. + +The dashboards Python teams typically build fall into a few clear categories: + +- [Collection monitors](https://reflex.dev/templates/database-visualization/) that display document counts, update rates, and field-level stats across your Atlas cluster + +- Aggregation pipeline viewers that surface results from `$group`, `$match`, and `$unwind` stages as interactive charts + +- User activity trackers pulling event documents and displaying time-series breakdowns + +- Analytics interfaces for time-series data, where documents arrive continuously and the UI needs to refresh without a full page reload + +Where relational dashboards flatten everything into tables, MongoDB dashboards often surface hierarchy. A single order document might contain a nested location object, a line-items array, and embedded metadata. Your UI needs to handle that gracefully, either flattening it selectively or displaying expandable rows and grouped visualizations. + +[MongoDB Charts](https://www.mongodb.com/products/platform/atlas-charts/dashboard) handles some of this natively, connecting directly to Atlas data for real-time analytics. But it is opinionated, limited on customization, and cannot replace a full app with business logic, auth, and custom workflows. That is the gap a Python-built dashboard fills. + +## Why Python Developers Choose Reflex for MongoDB Dashboards + +Python is already the dominant language for working with MongoDB. PyMongo uses syntax close to the MongoDB shell, so the queries your team already writes map directly into a Reflex backend with no translation layer. The data stays in Python the whole way through, from the collection query to the UI component that displays it. + +That's the core argument for Reflex here. JavaScript frameworks split your MongoDB logic from your UI across two languages, two build systems, and often two teams. With Reflex, a single Python file can hold your PyMongo queries, your state management, and your 60+ built-in components for tables, charts, and stat cards. Domain experts who wrote the data models can read and modify the dashboard code without touching a line of JavaScript. + +MongoDB Charts fills a narrow slice of this need. It connects to Atlas, runs fast, and requires no code. But you cannot add auth flows, custom business logic, or multi-page navigation. The moment your [dashboard](https://reflex.dev/templates/admin-console-dashboard/) needs a filter that calls a Python function or a page that only certain users can see, Charts hits a wall. + +Reflex does not have that constraint. Browse the [template gallery](https://reflex.dev/templates/) and you will find production-ready dashboard patterns your team can fork, connect to MongoDB, and ship in minutes, not days. + +| Capability | Reflex | MongoDB Charts | JavaScript Frameworks | +|---|---|---|---| +| Language | Pure Python for backend and frontend with PyMongo queries written directly in event handlers | No-code interface with visual configuration and Atlas integration | JavaScript or TypeScript for frontend with separate Python or Node.js backend for MongoDB queries | +| Custom Business Logic | Full Python logic in state classes with custom authentication, workflows, and data processing pipelines | Limited to built-in filtering and aggregation options with no custom code execution | Complete flexibility but requires coordinating logic across frontend and backend codebases | +| Nested Document Handling | Expandable tables, grouped visualizations, and state-layer flattening with default values for missing fields | Automatic flattening with limited control over nested structure display | Requires manual component development to handle variable schemas and nested arrays | +| Real-time Updates | WebSocket-based state sync with automatic UI updates when aggregation pipeline results change | Auto-refresh on configurable intervals with manual refresh option | Manual WebSocket or polling implementation with separate state management library | +| Multi-page Applications | Built-in routing with shared state across pages and navigation components | Single-page dashboards only with no navigation or multi-view support | Full routing capabilities but requires configuring separate frontend routing library | +| Deployment | Single command deployment with multi-region options and automatic proximity to Atlas clusters | Hosted by MongoDB with no deployment configuration required | Separate deployment for frontend and backend with manual infrastructure configuration | + +## Connecting MongoDB to Your Reflex App + +Because Reflex runs Python on the backend, PyMongo calls live directly inside your state classes and event handlers. There is no middleware layer, no REST proxy, no separate server bridging your database to your frontend. Install `pymongo` via pip and write connection logic the same way you would in any Python script, except now it feeds directly into UI state that updates in real time. + +PyMongo [connects using a standard connection string](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/) that works across Atlas cloud clusters, local instances, and replica sets. Your development environment and production Atlas cluster use the same connection pattern, with the string as the only variable that changes between them. + +Where Reflex's architecture earns its keep is at the project level. Instead of configuring a MongoDB connection string per app, Reflex centralizes integration credentials across all applications in a project. Build three dashboards off the same Atlas cluster and they all reference one shared configuration, with no copy-pasting secrets and no per-app reconfiguration when credentials rotate. + +This matters especially for teams building multiple MongoDB dashboards, whether that's a collection monitor, an analytics view, or an ops tool, since each new app inherits the connection automatically. + +## Key Dashboard Components for MongoDB Data + +MongoDB's document model shapes your component choices more than anything else. Flat relational data fits neatly into a [standard table](https://reflex.dev/blog/using-table-component/). Nested documents, embedded arrays, and variable fields need UI that can handle hierarchy without collapsing everything into one unreadable row. + +A few component patterns cover most MongoDB dashboard needs: + +- [Stat cards](https://reflex.dev/templates/finance-dashboard/) for real-time metrics like document counts, insert rates, and collection sizes, giving users an at-a-glance reading of database activity without querying manually + +- Line charts for time-series collections where documents arrive continuously and trends need to be visible across configurable time windows + +- [Bar or pie charts](https://reflex.dev/blog/graphing-update/) for aggregation pipeline results from `$group` and `$facet` stages, where summarizing large collections into digestible breakdowns matters + +- [Expandable tables](https://reflex.dev/blog/using-ag-grid-in-reflex/) for document arrays where nested objects need drilldown instead of a flattened, context-losing row format + +The state management pattern is where things click. MongoDB aggregation pipelines run inside backend event handlers as regular Python functions. Computed vars built from that pipeline output update the UI automatically when state changes. No polling loop, no client-side JavaScript, no manual refresh trigger. The browser reflects what the database returns as soon as the query completes, which is exactly what analytics dashboards need when documents arrive at high frequency. + +### Handling Variable Schema Fields + +MongoDB collections often contain documents with inconsistent field sets. Your UI needs a fallback strategy for missing keys instead of throwing a render error. A clean approach is to define default values at the state layer before data reaches your components, so every chart or table always receives a predictable structure regardless of what the raw document contains. + +## Deploying Your MongoDB Dashboard to Production + +Reflex packages your entire PyMongo connection logic, query code, and UI into a single deployable unit. There is no separate frontend build step, no API server to configure independently. One command handles it all, documented in the deploy quick start. + +[Multi-region deployment](https://reflex.dev/hosting/) lets you place your dashboard close to your Atlas cluster, cutting round-trip latency on heavy aggregation queries. CI/CD hooks for GitHub Actions and GitLab CI mean schema changes or dashboard updates ship automatically without manual intervention. + +For teams connecting to internal MongoDB instances behind firewalls, VPC and on-premises options keep data inside controlled environments while the full application runs on your infrastructure. Whether your cluster lives in Atlas or a self-hosted replica set, the deployment architecture adjusts without changing application code. + +## FAQ + +### Can I build a MongoDB dashboard without JavaScript? + +Yes. Reflex lets you build full MongoDB dashboards in pure Python, using PyMongo queries directly in your backend event handlers without writing any JavaScript. + +### MongoDB Charts vs Reflex for building dashboards? + +MongoDB Charts works well for basic analytics with zero code, but Reflex gives you full control to add authentication, custom business logic, multi-page navigation, and complex workflows that Charts cannot handle. If you need more than simple visualizations, Reflex is the better choice. + +### How do I handle nested MongoDB documents in dashboard tables? + +Use expandable tables for nested arrays and objects, or flatten data selectively at the state layer with default values for missing fields. This prevents render errors when documents have inconsistent schemas while preserving the hierarchical structure where it matters. + +### What's the fastest way to connect PyMongo to a Reflex dashboard? + +Install `pymongo` via pip and write connection logic directly in your Reflex state classes using your MongoDB connection string. Reflex stores integration credentials at the project level, so multiple dashboards automatically inherit the same Atlas cluster connection without reconfiguring each app. + +### When should I use computed vars for MongoDB aggregation results? + +Use computed vars when your aggregation pipeline results depend on state variables that change based on user interactions. The UI updates automatically when state changes, giving you real-time dashboard updates without manual polling or refresh triggers. diff --git a/blog/build-dashboard-openai.md b/blog/build-dashboard-openai.md new file mode 100644 index 000000000..056f41d3e --- /dev/null +++ b/blog/build-dashboard-openai.md @@ -0,0 +1,155 @@ +--- +author: Tom Gotsman +date: 2026-04-07 +title: "How to Build a Dashboard With OpenAI in 2026" +title_tag: "Build OpenAI Dashboard Python 2026" +description: "Learn how to build a dashboard with OpenAI in April 2026. Track token usage, costs, and latency across gpt-5.4, gpt-5-mini, and gpt-5-nano in pure Python." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "OpenAI dashboard Python, GPT dashboard, token usage dashboard, OpenAI API metrics, AI cost tracking, LLM monitoring dashboard" + } +] +faq: [ + {"question": "Can I build an OpenAI dashboard without learning JavaScript?", "answer": "Yes. Reflex lets you build full OpenAI monitoring dashboards entirely in Python, covering API usage tracking, token consumption analysis, cost management, and real-time request monitoring without writing any JavaScript."}, + {"question": "What's the best way to handle OpenAI streaming responses in a Python dashboard?", "answer": "Reflex's WebSocket-based state sync handles streaming OpenAI responses natively, pushing live token counts and real-time cost updates to your dashboard without polling. The event-driven state model keeps dashboard logic organized as you scale from single usage charts to multi-model comparison views across gpt-5.4, gpt-5-mini, and gpt-5-nano."}, + {"question": "How do I track OpenAI API costs across multiple models in 2026?", "answer": "Install the OpenAI Python SDK with `pip install openai` and integrate it directly into your Reflex state classes. Use computed vars to calculate rolling averages and cost projections server-side, then display them through stat cards showing total requests, cumulative token spend, average cost per request, and breakdowns by model tier (gpt-5.4, gpt-5-mini, gpt-5-nano)."}, + {"question": "Streamlit vs Reflex for OpenAI dashboards?", "answer": "Streamlit's script rerun model causes memory leaks and requires full re-execution on every interaction, making it unsuitable for real-time OpenAI monitoring. Reflex's event-driven architecture and WebSocket sync handle live request feeds and streaming response monitoring without performance degradation, and the professional UI won't need replacing when you move to production."}, + {"question": "When should I deploy an OpenAI dashboard on-premises instead of cloud?", "answer": "If your finance team handles sensitive cost data, you connect to internal billing systems, or compliance requirements prevent external hosting of API usage metrics, deploy your Reflex dashboard via VPC or on-premises options. The entire stack runs within your security perimeter while maintaining all monitoring capabilities."}, + {"question": "How does Reflex handle live updates for OpenAI token consumption without polling?", "answer": "Reflex uses WebSocket-based state sync to push updates instantly to your dashboard, eliminating the need for polling hacks. This means live token counts, real-time cost updates, and streaming response monitoring stay current without page refreshes or interval-based checks."}, + {"question": "What components do I need for a production OpenAI monitoring dashboard?", "answer": "A production dashboard typically includes stat cards for key metrics (total requests, token spend, cost per request), time-series charts for token trends and model comparisons, data tables for granular request logs showing timestamp and cost per call, and real-time request monitoring for error tracking and latency spikes."}, + {"question": "Can I use the full PyPI ecosystem with Reflex for OpenAI integrations?", "answer": "Yes. Reflex's backend runs on FastAPI, which means any Python library from PyPI, including the OpenAI SDK, drops in directly. You install it with pip install openai and import it inside your Reflex state classes exactly as you would in any Python project, with no adapter libraries or middleware needed."}, + {"question": "How do I rotate OpenAI API keys across multiple dashboards?", "answer": "Reflex uses project-level integration configuration, meaning you configure API keys once at the project level and they're shared across every app in that project. When you rotate an OpenAI key, you change it in one place and every dashboard picks it up automatically without managing separate configurations."}, + {"question": "What happens when OpenAI changes their API endpoints?", "answer": "When OpenAI transitions endpoints (like the planned Assistants API to Responses API migration), you locate and fix the exact Python function in your readable state classes. Since the entire stack is pure Python, this becomes a five-minute fix rather than digging through minified JavaScript across separate frontend and backend layers."}, + {"question": "Can I deploy an OpenAI dashboard automatically with CI/CD?", "answer": "Yes. Reflex supports multi-region deployment with CI/CD integration via GitHub Actions, letting you push to main and trigger an automated dashboard update. The entire stack—OpenAI polling logic, state classes, WebSocket handlers, and UI—ships as one unit with no separate deployment steps."}, + {"question": "How do I store API credentials securely in a Reflex OpenAI dashboard?", "answer": "Store your OpenAI API key as an environment variable following standard Python security practices. Reflex state classes read from environment variables the same way any Python application does, and project-level configuration makes credentials available across monitoring views without duplication or hardcoding in source code."}, + {"question": "What's the difference between building dashboards with Reflex versus code generation tools like Lovable?", "answer": "Code generation tools like Lovable output JavaScript dashboards that Python teams can't maintain or audit, creating long-term overhead. Reflex keeps the entire stack in Python—the same language as your OpenAI API code, data models, and business logic—eliminating context-switching and maintenance burden."}, + {"question": "Can I analyze OpenAI usage data with pandas in a Reflex dashboard?", "answer": "Yes. Python scripts can fetch data from OpenAI APIs, process it with pandas and matplotlib for visualization, then store in databases or export as CSV/JSON for longer retention. Computed vars in Reflex state classes handle rolling averages and cost projections server-side, keeping analytics logic in readable Python rather than client-side scripts."}, + {"question": "How many built-in components does Reflex provide for dashboard building?", "answer": "Reflex includes 60+ built-in components covering charts, tables, and data displays without requiring third-party installs. This covers visualization needs for OpenAI monitoring like line charts for token trends, bar charts for model comparisons, stat cards for metrics, and data tables for request logs."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Building an OpenAI dashboard in pure Python prevents surprise API bills by tracking token usage, costs, and latency across models like gpt-5.4, gpt-5-mini, and gpt-5-nano in real-time. +- Reflex handles streaming responses natively through WebSocket state sync, eliminating polling hacks for live monitoring. +- Project-level API key configuration means rotating credentials once updates every dashboard you deploy. +- Deploy to production with a single command that packages Python backend and UI together, making endpoint updates a five-minute fix. +- Reflex is a full-stack Python framework for building production web apps without JavaScript, used by 40% of Fortune 500 companies for internal tools. + +## What You Can Build: OpenAI Dashboard Overview + +Building an OpenAI dashboard sounds straightforward until you're three weeks into a project and your API bill doubles overnight with no clear explanation. That's the real problem these dashboards solve: visibility. Without one, engineering teams are flying blind across model tiers, endpoints, and cost centers. + +With Reflex, you can build a production-grade OpenAI monitoring dashboard that tracks what actually matters to your team. You can start from one of our [pre-built templates](https://reflex.dev/templates/) or build from scratch. Here's what falls within scope: + +- API usage tracking across endpoints and user sessions +- Token consumption analysis broken down by model (gpt-5.4, gpt-5-mini, gpt-5-nano) +- Cost management with per-request and cumulative spend views +- Response time monitoring and latency trends over time +- Real-time request analytics with live state updates + +The use cases span teams. An engineering lead might watch token burn rates across model tiers to decide whether gpt-5-mini covers 80% of requests as cheaply as gpt-5-nano would. A finance team member wants weekly cost rollups without touching a terminal. A product manager needs to know which features drive the most API consumption. One dashboard can serve all three, built entirely in Python. + +> +OpenAI monitoring integrations provide insights into token usage rates, response times, and overall costs, empowering teams to make data-driven decisions while keeping OpenAI API usage in check. + +The goal is not a pretty chart. It's preventing a $40,000 surprise at the end of the month. + +## Why Python Developers Choose Reflex for OpenAI Dashboards + +Python developers building OpenAI integrations generally have no interest in maintaining a separate React frontend. The code calling the API is Python. The data models are Python. The business logic is Python. Switching to JavaScript just to render a chart introduces friction that compounds fast. + +Reflex keeps the entire stack in one language. Data scientists and ML engineers can build OpenAI dashboards using the same mental model they already apply to their API code, with no context-switching, no npm installs, and no TypeScript errors at midnight. + +A few specific reasons Python teams land on Reflex over alternatives: + +- WebSocket-based state sync handles streaming OpenAI responses natively, so live token counts and real-time cost updates work without polling hacks. +- The event-driven state model keeps dashboard logic organized as you scale from a single usage chart to multi-model comparison views across gpt-5.4, gpt-5-mini, and gpt-5-nano. +- 60+ built-in components cover charts, tables, and data displays without third-party installs. +- Code generation tools like Lovable output JavaScript dashboards your Python team can't maintain or audit, which creates long-term overhead that pure Python avoids entirely. + +Delta Global's Head of Quant put it plainly: Reflex is "like Streamlit for adults", fast, professional, and something you won't throw away after prototyping. Learn more about [Reflex vs Streamlit](https://reflex.dev/blog/reflex-streamlit/) differences. That's the bar an OpenAI dashboard should clear. + +## Connecting OpenAI to Your Reflex App + +Reflex's backend runs on FastAPI, which means the OpenAI Python SDK drops in exactly as it would in any other Python project. No middleware layer, no adapter libraries, no separate backend service to maintain. + +### Backend Integration Pattern + +Since Reflex supports the full PyPI ecosystem, you install the OpenAI library with `pip install openai` and import it directly inside your Reflex state classes. The library covers every OpenAI REST endpoint with both synchronous and asynchronous clients, and ships with type definitions for all request params and response fields, so your IDE catches errors before runtime. + +Where Reflex pulls ahead for teams managing multiple dashboards is project-level integration configuration. API keys and credentials are configured once at the project level and shared across every app in that project. For long-running API calls, check out [background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) to keep your UI responsive. When you rotate an OpenAI key, you change it in one place and every dashboard picks it up automatically. + +### API Authentication Setup + +Store your OpenAI API key as an environment variable following standard Python security practices. Reflex state classes read from environment variables the same way any Python application does, and project-level configuration makes that credential available across multiple monitoring views without duplication. Teams building separate dashboards for cost tracking, latency analysis, and model comparison across models like gpt-5, gpt-5-mini, or gpt-5-nano do not manage three separate key configurations. One credential, one rotation process, one access control policy covering everything you deploy. + +## Key Dashboard Components for OpenAI Data + +Good dashboards are built from composable pieces. Before wiring up data sources, it helps to know which components carry the most weight for an OpenAI monitoring use case. + +### Metrics and Stat Cards + +Stat cards are the first thing anyone looks at: total requests, cumulative token spend, average cost per request, and API response time. Our [finance dashboard template](https://reflex.dev/templates/finance-dashboard/) shows effective patterns for displaying cost metrics. Computed vars in your state classes handle rolling averages and cost projections server-side, so the analytics logic lives in readable Python instead of scattered across client-side scripts. For deeper insights on which [API metrics SaaS teams track](https://www.cloudzero.com/blog/api-metrics/) to connect usage with costs, CloudZero's guide covers the core indicators that matter for scaling profitably. + +### Time-Series Charts and Usage Tables + +Standard Python visualization techniques using pandas and matplotlib give you deeper insights when displaying OpenAI usage over time. You get [line and bar charts](https://reflex.dev/blog/graphing-update/) for model comparisons across gpt-5.4, gpt-5-mini, and gpt-5-nano without writing JavaScript. The OpenAI Usage API returns time-bucketed results that map cleanly to reactive chart updates. For granular request logs, [a data table](https://reflex.dev/blog/using-table-component/) showing timestamp, model, tokens, and cost per call covers the detail layer. Python scripts regularly fetch data from OpenAI APIs, process with pandas, then store in databases or export as CSV/JSON for longer retention. + +### Real-Time Request Monitoring + +Polling misses events. WebSocket-based state sync pushes updates instantly, which matters when debugging a production LLM application where a spike in errors or latency happens in under a second. Live request feeds, streaming response monitoring, and error tracking all stay current without page refreshes or interval hacks. + +| Dashboard Component | OpenAI Data Type | Reflex Component | Update Pattern | +|---|---|---|---| +| Cost Summary | Aggregated spend | Stat cards | Daily refresh | +| Token Usage Chart | Time-series metrics | Recharts line chart | Real-time WebSocket | +| Model Comparison | Per-model statistics | Bar chart | On-demand calculation | +| Request Log | Individual API calls | Data table | Live event stream | +| Error Rate Monitor | Failure metrics | Badge + stat | Real-time alerts | + +## Deploying Your OpenAI Dashboard to Production + +Once your dashboard is ready, [deploying with Reflex](https://reflex.dev/hosting/) requires a single command that packages the entire stack together. The OpenAI Usage API polling logic, state classes, WebSocket handlers, and visualization components all ship as one unit, with no separate steps for the Python layer and the compiled UI. + +That cohesion carries real weight. OpenAI [announced Assistants API transitions to Responses API](https://developers.openai.com/api/docs/changelog), with an anticipated 2026 sunset date. When endpoints change, you need to locate and fix the exact Python function handling that integration. Readable state classes make that a five-minute fix instead of a multi-hour dig through minified JavaScript. + +### Enterprise Deployment Options + +For global teams tracking OpenAI spend across regions, there are a few deployment paths worth knowing about: + +- Multi-region deployment with CI/CD integration via GitHub Actions lets you push to main and trigger an automated dashboard update, with no manual re-deploys required. +- VPC and on-premises deployment runs the full dashboard within your security perimeter, satisfying compliance requirements without sacrificing any monitoring capability. For containerized deployments, see our guide on [self-hosting Reflex with Docker](https://reflex.dev/blog/self-hosting-reflex-with-docker/). +- Environment-specific settings propagate cleanly across deployments through the app configuration layer, keeping credentials and endpoint URLs out of your source code. + +Finance teams handling sensitive cost data or connecting to internal billing systems will find the self-hosted path especially practical, since the entire stack stays within infrastructure you control. + +## FAQ + +### Can I build an OpenAI dashboard without learning JavaScript? + +Yes. Reflex lets you build full OpenAI monitoring dashboards entirely in Python, covering API usage tracking, token consumption analysis, cost management, and real-time request monitoring without writing any JavaScript. + +### What's the best way to handle OpenAI streaming responses in a Python dashboard? + +Reflex's WebSocket-based state sync handles streaming OpenAI responses natively, pushing live token counts and real-time cost updates to your dashboard without polling. The event-driven state model keeps dashboard logic organized as you scale from single usage charts to multi-model comparison views across gpt-5.4, gpt-5-mini, and gpt-5-nano. + +### How do I track OpenAI API costs across multiple models in 2026? + +Install the OpenAI Python SDK with `pip install openai` and integrate it directly into your Reflex state classes. Use computed vars to calculate rolling averages and cost projections server-side, then display them through stat cards showing total requests, cumulative token spend, average cost per request, and breakdowns by model tier (gpt-5.4, gpt-5-mini, gpt-5-nano). + +### Streamlit vs Reflex for OpenAI dashboards? + +Streamlit's script rerun model causes memory leaks and requires full re-execution on every interaction, making it unsuitable for real-time OpenAI monitoring. Reflex's event-driven architecture and WebSocket sync handle live request feeds and streaming response monitoring without performance degradation, and the professional UI won't need replacing when you move to production. + +### When should I deploy an OpenAI dashboard on-premises instead of cloud? + +If your finance team handles sensitive cost data, you connect to internal billing systems, or compliance requirements prevent external hosting of API usage metrics, deploy your Reflex dashboard via VPC or on-premises options. The entire stack runs within your security perimeter while maintaining all monitoring capabilities. diff --git a/blog/build-dashboard-resend-python.md b/blog/build-dashboard-resend-python.md new file mode 100644 index 000000000..1a4bfef04 --- /dev/null +++ b/blog/build-dashboard-resend-python.md @@ -0,0 +1,143 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Resend in 2026" +title_tag: "Build a Resend Dashboard in 2026" +description: "Learn how to build a Resend dashboard in April 2026. Track delivery rates, bounces, and email engagement metrics with Python integration." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Resend dashboard Python, email analytics dashboard, Resend API metrics, email delivery tracking, transactional email dashboard" + } +] +faq: [ + {"question": "Can I build a Resend dashboard without JavaScript?", "answer": "Yes. Reflex lets you build a complete Resend integration dashboard in pure Python, handling both API calls and webhook processing without writing any JavaScript. The framework compiles to a FastAPI backend and manages the frontend automatically, so you can fetch email event data, process webhooks, and render real-time charts using only Python event handlers and state classes."}, + {"question": "What's the fastest way to monitor Resend delivery metrics in 2026?", "answer": "Connect Resend webhooks to a Reflex app using API routes, store incoming events in state classes, and render metrics with built-in components like datatable and recharts. You can have a working dashboard tracking delivery rates, bounce patterns, and engagement metrics within a few hours, since Reflex handles webhook infrastructure and UI rendering without separate frontend development."}, + {"question": "How do I process Resend webhooks in a Reflex dashboard?", "answer": "Register a webhook endpoint through Reflex's API route system, which exposes a FastAPI endpoint that receives Resend's POST payloads. Your Python event handler parses the payload, updates state classes with delivery status or bounce data, and computed vars automatically recalculate metrics like delivery rate. For heavy processing across thousands of events, background tasks handle aggregation asynchronously without blocking the interface."}, + {"question": "What metrics should a production Resend dashboard track?", "answer": "Track delivery rate over time (sent vs. delivered vs. failed), bounce rate segmented by hard and soft bounces, open and click rates per campaign, suppression list growth, complaint spikes, and transactional email latency for time-sensitive sends like password resets. These metrics surface infrastructure issues, reputation problems, and campaign performance without requiring CSV exports or third-party analytics tools."}, + {"question": "How does Reflex handle real-time updates when Resend webhooks fire?", "answer": "Reflex's FastAPI backend receives webhook POST payloads through API routes, and Python event handlers immediately update state classes with the new data. Computed vars then automatically recalculate derived metrics, and dashboard components re-render without requiring polling or client-side refresh logic."}, + {"question": "Can I use the Resend Python SDK with async operations in Reflex?", "answer": "Yes. The Resend Python SDK supports async operations via httpx and custom HTTP client configurations, which integrates naturally with Reflex's event handlers. You can make asynchronous API calls to Resend directly from your Reflex state classes without blocking the UI."}, + {"question": "What are the main advantages of building a Resend dashboard in Reflex versus custom JavaScript?", "answer": "Reflex keeps your entire codebase in Python, making it debuggable by backend engineers at 2 AM without needing frontend specialists. You get 60+ built-in components for metrics visualization, automatic state management, and the ability to trace exactly which event handler updates which chart without hunting through separate JavaScript bundles."}, + {"question": "How should I store Resend API keys in a production Reflex deployment?", "answer": "Store Resend API keys as environment variables rather than hardcoding them anywhere. This keeps secrets out of version control, allows credential rotation without code changes, and lets project-level integration configuration share credentials across multiple dashboard applications."}, + {"question": "What deployment options does Reflex support for compliance-sensitive teams?", "answer": "Reflex supports VPC or on-premises deployment for finance and healthcare teams needing data isolation, Kubernetes orchestration via Helm charts for GitOps workflows, and multi-region support for high-volume campaigns. All deployment methods can securely connect to Resend's public API while meeting strict security requirements."}, + {"question": "Can I customize visualizations beyond Reflex's built-in charting components?", "answer": "Yes. While Reflex includes recharts integration for common visualizations like line charts and bar charts, you can wrap third-party React charting libraries for specialized views like funnel charts. This lets you access the full JavaScript visualization ecosystem while keeping your data structures and logic typed in Python."}, + {"question": "How does Reflex handle webhook processing for thousands of email events?", "answer": "Reflex's background tasks process heavy aggregation work asynchronously without blocking the UI. When webhooks deliver thousands of bounce records or engagement events, background tasks handle the processing while computed vars derive metrics from the updated state, keeping your dashboard responsive."}, + {"question": "What's the difference between using Reflex API routes versus spinning up separate webhook infrastructure?", "answer": "Reflex compiles to a FastAPI backend, so you register webhook endpoints directly through its API route system without deploying separate servers. This eliminates infrastructure overhead and keeps your webhook processing logic in the same codebase as your dashboard UI and state management."}, + {"question": "How do I segment bounce data by hard versus soft bounces in a Reflex dashboard?", "answer": "Parse the bounce type from Resend's webhook payload in your event handler, store it in your state class with categorical fields, and use computed vars to filter and aggregate by bounce category. You can then render separate metrics or a bar chart showing hard versus soft bounce counts using Reflex's recharts components."}, + {"question": "What monitoring capabilities does Reflex provide for production dashboards?", "answer": "Reflex includes built-in monitoring that surfaces dashboard response times and webhook throughput without requiring separate APM tools. This keeps your observability stack lean while tracking critical metrics like processing latency and system performance as you scale."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build a live Resend dashboard in Python that tracks delivery rates, bounces, and engagement metrics without writing JavaScript. + +- Reflex connects to Resend's API and webhooks through Python event handlers, letting you process email events in real-time using the same language as your backend logic. + +- Deploy with VPC isolation for compliance-sensitive teams or use Kubernetes orchestration for high-volume broadcast campaigns. + +- Reflex is a full-stack Python framework that lets you build production web apps entirely in Python, used by 40% of Fortune 500 companies for internal tools. + +## What You Can Build: Resend Dashboard Overview + +Resend emits webhook events for every meaningful moment in an email's lifecycle: delivered, opened, clicked, bounced, complained. Feed those events into a Reflex app and you get a live production dashboard that your engineering and growth teams can act on, without waiting for a third-party analytics tool to catch up. + +> + +Resend processes terabytes of email event logs while maintaining 62ms average query latency for its Marketing Analytics dashboards, proving that email event data at scale demands purpose-built infrastructure, not afterthought reporting. + +Here is what a [well-scoped Resend dashboard](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) tracks at minimum: + +- Delivery rate over time, broken into sent, delivered, and failed, so you can spot infrastructure or reputation issues before they compound. + +- Bounce rate segmented by hard vs. soft bounces, giving you the granularity to act on permanent failures separately from temporary ones. + +- Open and click rates per campaign or template, letting growth teams compare performance across sends without exporting CSVs. + +- Suppression list growth and complaint spikes, which are early warning signals for deliverability problems. + +- Transactional email latency for receipts, password resets, and alerts, where slow delivery has a direct impact on user trust. + +The dashboard scope here stays read-only: pulling and aggregating event logs into clear signal, not pushing changes back to Resend's sending configuration. + +## Why Python Developers Choose Reflex for Resend Dashboards + +Resend's Python SDK supports async operations via httpx and lets you configure custom HTTP clients with timeout settings, which fits naturally into how Reflex works. The [Resend Python SDK](https://github.com/resend/resend-python) slots directly into Reflex's event handlers, so your backend calls the Resend API without any JavaScript middleware sitting between your logic and your data. + +The whole dashboard lives in one Python codebase. State classes hold your email event data, 60+ built-in components render metrics tables and time-series charts, and computed vars aggregate bounce rates or engagement trends without a single line of client-side code. When you need specialized visualizations beyond what ships out of the box, Reflex's React wrapping capability gives you access to the full JS ecosystem while keeping your types and logic in Python. + +The practical payoff shows up at 2 AM. When a delivery anomaly spikes, an email infrastructure engineer can open the Reflex codebase and read exactly which state variable is feeding which chart, trace the event handler that last updated the suppression count, and fix it without needing a frontend specialist on the call. [Code generation tools](https://reflex.dev/blog/custom-components/) that output standalone JavaScript don't offer that. The running code matches what your team wrote, which makes it debuggable by the same people who understand your sending infrastructure. + +## Connecting Resend to Your Reflex App + +Getting Resend connected to a Reflex app involves two distinct integration points: the REST API for querying historical email data, and webhooks for receiving live delivery events as they happen. + +### API Key Configuration and Project-Level Integration + +Resend API keys live in your Resend Dashboard under API settings. Once you have one, store it as an environment variable instead of hardcoding it anywhere. Reflex's project-level integration configuration then shares that credential across every dashboard application within the project, so a transactional email monitor and a broadcast campaign dashboard can both access [Resend](https://resend.com) without separate authentication setups. Install the SDK with ``[pip install resend](https://pypi.org/project/resend/) and point it at your key through the environment. From there, any Reflex state class can call the Resend API directly from a Python event handler. + +### Event Handlers and Webhook Processing + +[Resend sends real-time notifications](https://resend.com) to your server every time an email is delivered, opened, bounced, or clicked. Because Reflex compiles to a FastAPI backend, you register a webhook endpoint through Reflex's API route system without spinning up separate infrastructure. The endpoint receives Resend's POST payload, and a Python event handler updates the relevant state class immediately. + +For heavier processing, such as aggregating bounce records across thousands of sends, [Reflex's background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) handle the work asynchronously without blocking the UI. Computed vars then calculate metrics like delivery rate or complaint percentage from raw state, and dashboard components re-render automatically when those vars change. No polling. No client-side refresh logic. + +## Key Dashboard Components for Resend Data + +Resend surfaces rich metadata on every email event: sender email, recipient, subject line, timestamp, and delivery status. Reflex's component library maps cleanly to these data shapes without custom wiring. + +### Tables for Email Logs and Event History + +[Reflex's datatable component](https://reflex.dev/blog/using-table-component/) displays paginated email logs with sortable columns for timestamp, recipient, status, and event type. Map Resend's webhook payload fields to table columns using Python dictionaries, then bind that data to the table with column definitions for filtering delivered versus bounced emails or searching by recipient domain. Each row can link to a detail view showing bounce reasons or suppression list status. Computed vars handle filtering logic server-side so your UI stays declarative. + +### Time-Series Charts for Delivery and Engagement Metrics + +Resend event types include sent, delivered, and bounced, and you can count sends per day directly from webhook history. [Reflex's recharts integration](https://reflex.dev/blog/graphing-update/) builds line charts for daily send volume, stacked bar charts comparing deliveries against bounces, and area charts tracking engagement across campaign lifecycles. For specialized views like funnel charts, wrap third-party React charting libraries while keeping your data structures typed in Python. The [stat component](https://reflex.dev/blog/using-ag-grid-in-reflex/) is ideal for headline numbers like overall delivery rate or total complaints this week. + +| Component Type | Resend Data | Reflex Implementation | Use Case | +|---|---|---|---| +| DataTable | Email event logs | rx.data_table with paginated rows | View recent sends with status filtering | +| Line Chart | Daily send volume | rx.recharts.line_chart with time series | Monitor sending patterns over time | +| Stat Card | Delivery rate percentage | rx.stat with computed var | Display key metric at a glance | +| Bar Chart | Bounce reasons | rx.recharts.bar_chart with categorical data | Identify most common delivery failures | + +## Deploying Your Resend Dashboard to Production + +Once your dashboard is working locally, getting it into production requires handling credentials, infrastructure, and compliance requirements carefully. + +Resend is [GDPR and SOC 2 compliant](https://resend.com/features/email-api), so production deployments should manage API keys through environment variable configuration instead of hardcoded values. This keeps secrets out of version control and lets you rotate credentials without touching application code. + +For teams with strict data requirements, there are a few deployment approaches worth knowing: + +- [VPC or on-premises deployment](https://reflex.dev/blog/on-premises-deployment/) lets finance and healthcare teams isolate their dashboard infrastructure within existing security perimeters while still connecting to Resend's public API for email delivery data. + +- Kubernetes via Helm chart orchestration can deploy both the dashboard frontend and webhook workers together, fitting GitOps workflows across dev, staging, and production environments. + +- CI/CD integration through GitHub Actions supports automatic redeployment when queries change or new Resend metrics need visualization, keeping your dashboard in sync with your codebase. + +Multi-region support is worth considering if you're processing high-volume broadcast campaigns, since positioning webhook receivers closer to Resend's infrastructure reduces processing latency. [Built-in monitoring](https://reflex.dev/hosting/) surfaces dashboard response times and webhook throughput without requiring a separate APM tool, which keeps your observability stack lean as you scale. + +## FAQ + +### Can I build a Resend dashboard without JavaScript? + +Yes. Reflex lets you build a complete Resend integration dashboard in pure Python, handling both API calls and webhook processing without writing any JavaScript. The framework compiles to a FastAPI backend and manages the frontend automatically, so you can fetch email event data, process webhooks, and render real-time charts using only Python event handlers and state classes. + +### What's the fastest way to monitor Resend delivery metrics in 2026? + +Connect Resend webhooks to a Reflex app using API routes, store incoming events in state classes, and display metrics with built-in components like datatable and recharts. You can have a working dashboard tracking delivery rates, bounce patterns, and engagement metrics within a few hours, since Reflex handles webhook infrastructure and UI updates without separate frontend development. + +### How do I process Resend webhooks in a Reflex dashboard? + +Register a webhook endpoint through Reflex's API route system, which exposes a FastAPI endpoint that receives Resend's POST payloads. Your Python event handler parses the payload, updates state classes with delivery status or bounce data, and computed vars automatically recalculate metrics like delivery rate. For heavy processing across thousands of events, background tasks handle aggregation asynchronously without blocking the interface. + +### What metrics should a production Resend dashboard track? + +Track delivery rate over time (sent vs. delivered vs. failed), bounce rate segmented by hard and soft bounces, open and click rates per campaign, suppression list growth, complaint spikes, and transactional email latency for time-sensitive sends like password resets. These metrics surface infrastructure issues, reputation problems, and campaign performance without requiring CSV exports or third-party analytics tools. diff --git a/blog/build-dashboard-salesforce.md b/blog/build-dashboard-salesforce.md new file mode 100644 index 000000000..bff060852 --- /dev/null +++ b/blog/build-dashboard-salesforce.md @@ -0,0 +1,153 @@ +--- +author: Tom Gotsman +date: 2026-04-07 +title: "How to Build a Dashboard With Salesforce in 2026" +title_tag: "Build Salesforce Dashboard 2026" +description: "Learn how to build a Salesforce dashboard in April 2026. Connect to REST API, pull live pipeline data, and deploy in pure Python with step-by-step instructions." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Salesforce dashboard Python, Salesforce API dashboard, CRM dashboard, Salesforce metrics Python, sales analytics dashboard" + } +] +faq: [ + {"question": "Can I build a Salesforce dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full Salesforce dashboards in pure Python, including authentication, data queries, charts, and real-time filters. The same developer querying the Salesforce REST API writes the interactive UI, state management, and event handlers — all in Python, with no context switching to JavaScript."}, + {"question": "Reflex vs Streamlit for Salesforce dashboards?", "answer": "Reflex handles event-based interaction and real-time updates via WebSocket, while Streamlit's script rerun model causes memory leaks and full page reloads on every click. For Salesforce dashboards with role-based access, multi-page navigation, and filters that update without refreshing, Reflex delivers production-grade functionality that Streamlit can't match."}, + {"question": "How do I authenticate my Reflex app with Salesforce?", "answer": "Authentication runs through OAuth 2.0 or username/password with a security token using the `simple-salesforce` library. Store credentials as environment variables and reference them inside Reflex state classes. With Reflex's project-level integration configuration, you set Salesforce credentials once and every app in that project inherits them automatically."}, + {"question": "What Salesforce data can I display in a custom dashboard?", "answer": "You can pull data from standard and custom objects through the Salesforce REST API: sales pipeline by stage, opportunity tracking with close date forecasting, lead conversion rates over time, account activity history, and revenue attainment vs. quota. SOQL queries run in Reflex event handlers, and computed vars format API responses for chart components."}, + {"question": "When should I deploy my Salesforce dashboard on-premises vs cloud?", "answer": "Choose on-premises or VPC deployment when compliance requirements rule out shared cloud infrastructure. If your Salesforce data carries regulatory constraints or your organization requires credentials to stay inside the corporate security perimeter, Reflex supports Helm chart orchestration that integrates with existing Kubernetes environments and GitOps pipelines."}, + {"question": "How do I pull live Salesforce data into my dashboard without manual exports?", "answer": "Use the Salesforce REST API with the simple-salesforce Python library to query standard and custom objects directly from Reflex event handlers. Background jobs can refresh data on a schedule via FastAPI's async support, pushing updates to components via WebSocket without blocking user interactions or requiring manual exports."}, + {"question": "What advantages does Reflex offer over pre-built Salesforce dashboard tools?", "answer": "Reflex gives you full control over UI, state management, and event handlers in pure Python, while pre-built tools force you into rigid layouts and limited interactivity. You get multi-page navigation, role-based access controls, and filters that update without page reloads—functionality that pre-built tools often can't deliver without workarounds."}, + {"question": "Can I filter Salesforce dashboard data by sales rep, region, or date range?", "answer": "Yes. Reflex filter controls like rx.select and rx.date_picker trigger event handlers that re-query Salesforce with updated parameters, then push new data to all dependent components via WebSocket in real-time without requiring a page refresh."}, + {"question": "How does Reflex handle real-time Salesforce data updates in dashboards?", "answer": "When filters change or background jobs run, Reflex event handlers query the Salesforce REST API and write results into state. Updated data automatically pushes to chart and table components via WebSocket, ensuring users see current numbers without manual refreshes or stale data."}, + {"question": "What types of charts work best for Salesforce sales pipeline visualization?", "answer": "Line charts track revenue trends and opportunity progression over time, bar charts show deals by stage or performance by sales rep, and stat cards display total pipeline value and conversion rates. Reflex supports these through its charting library and Plotly integration, with computed vars handling aggregation server-side."}, + {"question": "Do I need separate frontend and backend repositories for a Reflex Salesforce dashboard?", "answer": "No. Reflex is a full-stack framework where backend state, API queries, and frontend UI are all written in Python within a single codebase. This eliminates the need for separate repos and the handoff delays that come with coordinating between frontend and backend developers."}, + {"question": "How do I set up role-based access control for different sales team members?", "answer": "Define RBAC permission layers in Python to control which data views territory reps, regional managers, and revenue leadership can access from the same Salesforce org. Configuring these permissions in code keeps them version-controlled and auditable rather than added as an afterthought."}, + {"question": "Can I schedule automatic data refreshes from Salesforce without blocking dashboard interactions?", "answer": "Yes. Reflex runs on FastAPI with async support, allowing background jobs to refresh Salesforce data on a schedule while users continue interacting with the dashboard. Query results write to state and push to components without blocking any user actions."}, + {"question": "What are the code reduction benefits of using Reflex for Salesforce dashboards?", "answer": "Real projects built on Reflex use roughly 50% less code than equivalent alternatives because you handle state management, event handlers, routing, and UI components all in Python without context switching. There's no separate frontend codebase or framework-specific workarounds for multi-page navigation and interactive filters."}, + {"question": "How do I integrate custom Salesforce objects into a Reflex dashboard?", "answer": "Query custom objects through the Salesforce REST API using SOQL in Reflex event handlers, just as you would with standard objects. The simple-salesforce library handles querying, updating, and upserting records, and JSON responses map directly to Reflex table and chart data structures with minimal transformation."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Build Salesforce dashboards in pure Python using Reflex and the simple-salesforce library + +- Pull live pipeline, opportunity, and revenue data via REST API without JavaScript + +- Deploy with one command to production with RBAC and multi-region scaling built-in + +- Reflex outputs maintainable Python code for full-stack Salesforce dashboards + +## What You Can Build: Salesforce Dashboard Overview + +Salesforce stores a massive amount of revenue data, but actually seeing it clearly is another story. Sales reps bounce between reports, managers pull exports, and leadership is always waiting for someone to compile the latest pipeline numbers. A custom dashboard changes that entirely. + +By connecting to the Salesforce REST API, you can pull data from standard and custom objects and surface it in a single interactive view. The [Salesforce Analytics REST API](https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/salesforce_analytics_rest_api.pdf) lets you integrate report and dashboard data into any web application, which means you can build custom dashboards and automate reporting tasks outside of the native Salesforce UI. + +In practice, that opens up a range of real use cases: + +- Sales pipeline by stage, rep, or region, giving teams an at-a-glance view of where deals stand without digging through individual records (see [Reflex templates](https://reflex.dev/templates/) for examples) + +- Opportunity tracking with close date forecasting so revenue leaders can spot slippage before it hits the quarter + +- Lead conversion rates over time to identify which sources and campaigns are actually driving closed business + +- Account activity and interaction history consolidated in one place instead of scattered across tabs and timelines + +- Revenue attainment vs. quota tracked live against targets, removing the lag between performance and visibility + +With the right setup, your dashboard filters in real-time, drills down by team or territory, and pulls fresh data on each session load. Sales ops teams, account executives, and revenue leaders all get the visibility they need without filing a report request or waiting on a weekly export. + +One note worth setting early: Salesforce's API supports read access to standard and custom objects out of the box. Write-back capabilities depend on your org's API permissions and how your connected app is configured. + +## Why Python Developers Choose Reflex for Salesforce Dashboards + +The core problem for most data teams isn't accessing Salesforce data. It's what happens after. You've got clean API responses, a working Python script, and a clear picture of what the dashboard should show. Then comes the choice: hand it off to a JavaScript developer, or limit yourself to whatever a pre-built tool can render. + +Reflex removes that tradeoff entirely. Because the full stack is Python, the same developer querying the Salesforce API can build the interactive UI around it. State management, event handlers, routing, real-time data updates via WebSocket, all written in Python, no context switching required. Reflex ships with 60+ built-in components, and you can wrap any React visualization library in pure Python as [custom components](https://reflex.dev/blog/custom-components/) if you need something more specialized for sales analytics. + +> + +"It's like Streamlit for adults. It's fast, it looks good, and we don't need to throw it away after prototyping." - Delta Global Head of Quant + +That last point matters more than it sounds. Streamlit and similar tools force you to accept rigid layouts and limited interactivity. If you need multi-page navigation, role-based access controls, or filters that update without a full page reload, you're either working around the framework or abandoning it. Reflex handles all of that natively, and real projects built on it use roughly 50% less code than equivalent alternatives. + +For teams deciding where to start, Reflex's template gallery includes [dashboard templates](https://reflex.dev/templates/real-time-sales-dashboard/) you can fork and extend, with setup covered in minutes. No JavaScript, no separate frontend repo, no handoff delay. + +## Connecting Salesforce to Your Reflex App + +Getting data out of Salesforce and into a Python app is straightforward once you understand the auth layer. The `simple-salesforce` library, a [Python REST API client](https://simple-salesforce.readthedocs.io/), handles the heavy lifting: querying, updating, and upserting records directly from Python scripts without manual HTTP wiring. Install it via pip, and your Reflex app can talk to Salesforce from the same backend where your state lives. + +### Authentication and API Access + +Authentication runs through OAuth 2.0 or username/password with a security token. Store credentials as environment variables and reference them inside Reflex state classes, never in frontend code. For teams managing multiple sales dashboards, Reflex's project-level integration configuration means you set Salesforce credentials once and every app in that project inherits them automatically. No per-app reconfiguration. + +### Query Patterns and Data Access + +Reflex event handlers are where your SOQL queries live. A handler fires, hits the Salesforce REST API, and writes results into state. Because Reflex runs on FastAPI with async support under the hood, [background jobs](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) can refresh that data on a schedule without blocking anything the user is doing. Computed vars then take raw API responses and shape them into exactly what your chart components expect: clean, formatted, ready to render. As [one integration guide notes](https://www.salesforceben.com/a-step-by-step-guide-to-salesforce-integration-with-python/), Python makes this connection simpler than most teams expect. + +## Key Dashboard Components for Salesforce Data + +A Salesforce dashboard is only as useful as what it shows and how fast it responds. Here's how the core component types map to real sales use cases. + +### Tables and Data Grids + +[Opportunity lists, lead queues, and account directories](https://reflex.dev/blog/using-table-component/) all start as tables. Reflex's built-in table component handles pagination, sorting, and filtering natively. Salesforce query results return as JSON that maps directly to Reflex table data structures, so there's minimal transformation work. For teams needing spreadsheet-like behavior, [AG Grid integration](https://reflex.dev/blog/using-ag-grid-in-reflex/) adds column grouping and inline editing without leaving Python. + +### Charts and Metrics Visualization + +Pipeline stage distributions, quota attainment, and revenue trends all need chart components. Reflex's charting library covers the common cases, and Plotly integration handles more complex financial charting. Computed vars handle the aggregation server-side, grouping Salesforce records by stage, rep, or time period before they ever reach the component. + +### Filters and Real-Time Updates + +When a user changes a date range or region filter, Reflex event handlers re-query Salesforce and push updated data to every dependent component via WebSocket. No manual refresh, no stale numbers sitting on screen. + +| Component Type | Salesforce Use Case | Reflex Implementation | +|---|---|---| +| Data Table | Opportunity lists, lead queues, account directories | rx.table with pagination and sorting | +| Stat Cards | Total pipeline value, closed deals, conversion rates | rx.card with computed metrics from state | +| Line Charts | Revenue trends, opportunity progression over time | Plotly integration via rx.plotly | +| Bar Charts | Deals by stage, performance by sales rep | rx.recharts or Plotly bar charts | +| Filter Controls | Date range, region, product filtering | rx.select, rx.date_picker with event handlers | + +## Deploying Your Salesforce Dashboard to Production + +Getting a dashboard from local development into production involves more than clicking a deploy button. You need to think about credential security, scaling across time zones, and access control before the first rep logs in. + +[One-command deployment](https://reflex.dev/hosting/) packages your entire Salesforce dashboard, including integration logic, UI components, and state management, without requiring separate frontend and backend pipelines. Salesforce credentials stay in environment variables, never touching the frontend layer. For sales teams spread across geographies, multi-region scaling keeps latency low regardless of where reps are logging in. GitHub Actions or GitLab CI can trigger automated redeploys whenever dashboard code changes, keeping your production environment in sync with your repo. + +### Enterprise Deployment Patterns + +CRM data often carries compliance requirements that rule out shared cloud infrastructure entirely. On-premises and [VPC deployments](https://reflex.dev/blog/reflex-databricks-partnership/) keep Salesforce credentials and all dashboard infrastructure inside the corporate security perimeter. Helm chart orchestration slots into existing Kubernetes environments and GitOps pipelines without custom tooling. + +For sales dashboards, RBAC is worth configuring early. Territory reps, regional managers, and revenue leadership typically need different data views from the same Salesforce org. Defining those permission layers in Python keeps them version-controlled and auditable, not added as an afterthought once the dashboard is already in users' hands. + +## FAQ + +### Can I build a Salesforce dashboard without JavaScript? + +Yes. Reflex lets you build full Salesforce dashboards in pure Python, including authentication, data queries, charts, and real-time filters. The same developer querying the Salesforce REST API writes the interactive UI, state management, and event handlers, all in Python, with no context switching to JavaScript. + +### Reflex vs Streamlit for Salesforce dashboards? + +Reflex handles event-based interaction and real-time updates via WebSocket, while Streamlit's script rerun model causes memory leaks and full page reloads on every click. For Salesforce dashboards with role-based access, multi-page navigation, and filters that update without refreshing, Reflex delivers production-grade functionality that Streamlit can't match. + +### How do I authenticate my Reflex app with Salesforce? + +Authentication runs through OAuth 2.0 or username/password with a security token using the `simple-salesforce` library. Store credentials as environment variables and reference them inside Reflex state classes. With Reflex's project-level integration configuration, you set Salesforce credentials once and every app in that project inherits them automatically. + +### What Salesforce data can I display in a custom dashboard? + +You can pull data from standard and custom objects through the Salesforce REST API: sales pipeline by stage, opportunity tracking with close date forecasting, lead conversion rates over time, account activity history, and revenue attainment vs. quota. SOQL queries run in Reflex event handlers, and computed vars format API responses for chart components. + +### When should I deploy my Salesforce dashboard on-premises vs cloud? + +Choose on-premises or VPC deployment when compliance requirements rule out shared cloud infrastructure. If your Salesforce data carries regulatory constraints or your organization requires credentials to stay inside the corporate security perimeter, Reflex supports Helm chart orchestration that integrates with existing Kubernetes environments and GitOps pipelines. diff --git a/blog/build-dashboard-servicenow.md b/blog/build-dashboard-servicenow.md new file mode 100644 index 000000000..30cb37bdd --- /dev/null +++ b/blog/build-dashboard-servicenow.md @@ -0,0 +1,164 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With ServiceNow in 2026" +title_tag: "Build ServiceNow Dashboard 2026" +description: "Learn how to build a ServiceNow dashboard in April 2026. Connect REST APIs, display incidents, and create live dashboards without ServiceNow licenses." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "ServiceNow dashboard Python, ServiceNow API dashboard, ITSM dashboard, incident metrics Python, IT service analytics" + } +] +faq: [ + {"question": "Can I build a ServiceNow dashboard without JavaScript?", "answer": "Yes. Reflex lets you build complete ServiceNow dashboards in pure Python, including API calls, data transformation, and UI components, without writing any JavaScript."}, + {"question": "ServiceNow native dashboards vs Reflex dashboards?", "answer": "ServiceNow native dashboards require licensed user access and limit interactivity for external stakeholders. Reflex dashboards connect to ServiceNow's REST API and provide live, interactive views that anyone can access without an ITSM license, while supporting custom logic and third-party data merging."}, + {"question": "How do I connect ServiceNow APIs to my Reflex app?", "answer": "Install the ServiceNow API SDK via pip, configure your instance URL and authentication tokens at the project level, then write event handlers in your Reflex state class that fetch incident records or change requests directly. Reflex's backend handles all API calls server-side with credentials never exposed to the browser."}, + {"question": "What components do ServiceNow dashboards need?", "answer": "Most ServiceNow dashboards use stat cards for metrics like open ticket counts and SLA compliance, sortable data tables for incident lists with priority filters, time-series charts for trend analysis, and filter controls for status categories and assignment groups. Reflex provides these as built-in components."}, + {"question": "When should I deploy a custom ServiceNow dashboard instead of using native reports?", "answer": "If stakeholders without ServiceNow licenses need live data access, if you're merging ITSM data with external monitoring tools like Datadog, or if native dashboard limitations block the custom prioritization logic your team requires, a Reflex dashboard gives you the flexibility without BI tooling overhead."}, + {"question": "Can Reflex handle real-time updates from ServiceNow without constant polling?", "answer": "Yes, Reflex supports WebSocket connections that push ServiceNow updates to connected users automatically when incidents change state or tickets get reassigned. This keeps displayed metrics accurate without unnecessary API overhead from browser polling."}, + {"question": "What authentication methods does Reflex support for ServiceNow integration?", "answer": "Reflex supports both basic authentication for development environments and OAuth for production deployments. OAuth handles token rotation and scoped access across multiple integrated apps, with all credentials managed server-side so they never touch the browser."}, + {"question": "How does Reflex handle ServiceNow's nested relationships like incidents linked to problems?", "answer": "Reflex's class-based state model handles nested ServiceNow relationships through Python logic in state classes. This supports filtered queries, drill-down navigation, and cross-table state tracking without callback complexity or split frontend/backend state."}, + {"question": "Do I need separate BI tools to visualize ServiceNow data with Reflex?", "answer": "No, Reflex handles data retrieval, transformation, and visualization entirely in Python without requiring a separate BI layer. You can build production-grade visualizations using Reflex's 60+ built-in components or wrap any React component directly in Python."}, + {"question": "Can I merge ServiceNow data with other monitoring tools like Datadog or PagerDuty?", "answer": "Yes, because Reflex's backend runs entirely in Python, you can merge ITSM data from ServiceNow with metrics from external monitoring tools like Datadog or PagerDuty within the same state class and dashboard application."}, + {"question": "How do I implement role-based access control for my ServiceNow dashboard?", "answer": "Role-based access control can be implemented through Python logic in your Reflex application, checking user permissions before exposing incident records or change workflows. This ensures users only see records their ServiceNow roles permit, matching your organization's existing RBAC policies."}, + {"question": "What ServiceNow tables can I access through Reflex?", "answer": "The ServiceNow API SDK supports full CRUD operations on any ServiceNow table including incident, change_request, cmdb_ci for asset inventory, and sys_user for user assignment tracking. All tables are accessible via standard REST API endpoint patterns."}, + {"question": "Can I deploy my ServiceNow dashboard on-premises for security compliance?", "answer": "Yes, Reflex supports VPC and on-premises deployment options that keep ServiceNow credentials and sensitive ITSM data entirely within controlled infrastructure. This is important for enterprise teams in regulated industries with strict compliance requirements."}, + {"question": "How do I handle ServiceNow API rate limits in my dashboard?", "answer": "Implement graceful error handling in your Reflex event handlers to manage ServiceNow API rate limits and token expirations that may occur mid-session. For long-running data syncs, use background tasks to handle async operations without blocking the user interface."}, + {"question": "Does building a ServiceNow dashboard in Reflex require setting up middleware?", "answer": "No, the ServiceNow API SDK installs directly via pip and integrates into Reflex's backend without any middleware layer needed. API calls happen in event handlers within your state class, with no separate API layer or REST client configuration required."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build live ServiceNow dashboards in pure Python that display incidents, change requests, and CMDB data without requiring ServiceNow licenses for viewers + +- ServiceNow's REST API integrates directly into Reflex's backend via pip-installable Python libraries with no middleware layer needed + +- Reflex handles complex ServiceNow relationships (incidents linked to problems, assets tied to configuration items) through Python state classes that IT teams can read and modify + +- Project-level configuration lets you set ServiceNow credentials once and share them across multiple dashboard apps automatically + +- Reflex is an open-source Python framework that builds production web apps entirely in Python, used by 40% of Fortune 500 companies for internal tools + +## What You Can Build: ServiceNow Dashboard Overview + +ServiceNow sits at the center of most enterprise IT operations, processing incident tickets, change requests, asset management data, and performance metrics across the organization. That data is valuable. The problem is getting it in front of the right people fast enough to act on it. + +Native ServiceNow dashboards are interactive only for licensed users. Everyone else (service desk managers, department heads, executive stakeholders) gets a static export that's already stale by the time it lands in their inbox. [ServiceNow's own dashboard limitations](https://www.perspectium.com/blog/servicenow-dashboards/) push many teams toward building external views that pull live data and present it without requiring a full ITSM login. + +With Reflex, you can build those external views entirely in Python. Here's what teams typically build: + +- [Incident management dashboards](https://reflex.dev/templates/ticket-queue-management/) showing open ticket counts, severity breakdowns, and SLA compliance in real-time + +- [Change request trackers](https://reflex.dev/templates/deployment-and-health-dashboard/) with approval status, risk scores, and scheduled deployment windows + +- CMDB metrics reports visualizing asset health, coverage gaps, and configuration drift + +- Executive summaries that aggregate service availability and mean time to resolution across departments + +Each of these connects to ServiceNow's REST API, pulls structured data into a Python backend, and displays it through Reflex's component system. You get a live, interactive app that anyone can use without a ServiceNow license required. + +## Why Python Developers Choose Reflex for ServiceNow Dashboards + +ServiceNow's REST API returns clean, structured JSON covering incident records, CMDB assets, change requests, and performance metrics. Python handles that naturally. Libraries like `servicenow-api` are [available directly via pip](https://pypi.org/project/servicenow-api/), and they slot straight into Reflex's backend without any glue code or middleware layers. + +Drag-and-drop tools break down fast once requirements get specific. Applying custom prioritization logic to ticket queues, merging ITSM data with Datadog or PagerDuty metrics, building time-series charts with configurable thresholds: these are code problems, and they belong in a framework built for that purpose. + +Reflex's 60+ built-in components cover standard dashboard needs, and when you need a specialized charting library, you can wrap any React component directly in Python. You can also browse [pre-built templates](https://reflex.dev/templates/) to accelerate development. That means production-grade visualizations without touching JavaScript. + +### ServiceNow Data Complexity Requires Framework Flexibility + +ServiceNow tables carry nested relationships: incidents linked to problems, change requests tied to configuration items, assets connected to service dependencies. Surfacing those relationships in a dashboard requires filtered queries, drill-down navigation, and cross-table state tracking. + +Reflex's class-based state model handles all of that in Python logic. No callback spaghetti, no split frontend/backend state: just Python classes that IT domain experts on your team can read and modify without any frontend expertise required. + +## Connecting ServiceNow to Your Reflex App + +Reflex's backend runs entirely in Python, which means ServiceNow's REST API works natively from day one. The [ServiceNow API SDK](https://pypi.org/project/service-now-api-sdk/) installs via pip and supports full CRUD operations on any ServiceNow table (incidents, change requests, CMDB assets, user records) authenticating via API tokens or username/password credentials. That SDK lives in your Reflex state class alongside your dashboard logic, with no separate middleware required. + +Project-level integration configuration means you set your ServiceNow instance URL, authentication tokens, and OAuth parameters once. Every dashboard application within that project inherits those connection settings automatically, so you skip the repetitive credential wiring that plagues multi-app builds. + +Reflex event handlers are where the actual API calls happen. A handler fetches incident records, parses the JSON response, and updates dashboard state, all in Python. The UI updates automatically with no separate API layer and no REST client configuration file sitting in a different repo. + +### Authentication Patterns for ServiceNow APIs + +Basic authentication works for development environments. Production deployments typically require OAuth, which handles token rotation and scoped access across multiple integrated apps. Because Reflex's API routes live server-side, credentials never touch the browser. + +| ServiceNow Table | API Endpoint Pattern | Common Use Case | Data Type | +|---|---|---|---| +| incident | /api/now/table/incident | Track open support tickets | Tabular records | +| change_request | /api/now/table/change_request | Monitor deployment changes | Tabular records | +| cmdb_ci | /api/now/table/cmdb_ci | Asset inventory reporting | Hierarchical data | +| sys_user | /api/now/table/sys_user | User assignment tracking | Reference data | + +## Key Dashboard Components for ServiceNow Data + +ServiceNow's live data maps cleanly to a standard set of UI patterns. Knowing which components to reach for first saves real time. Here are the building blocks most ServiceNow dashboards need: + +- Stat cards showing open incident counts, SLA compliance rates, and mean time to resolution give operators an at-a-glance summary without needing to open a single ticket. + +- [Sortable data tables](https://reflex.dev/blog/using-table-component/) for incident lists with priority indicators and assignment group columns let teams quickly triage what needs attention and by whom. + +- [Time-series charts](https://reflex.dev/blog/graphing-update/) tracking ticket volume trends and resolution rates over configurable windows surface patterns that static reports miss entirely. + +- Filter controls for status categories, assignment groups, and date ranges let different teams slice the same data without separate dashboard builds. + +> + +ServiceNow dashboards use interactive visualizations like charts, graphs, and gauges that let users drill down, compare metrics, and detect anomalies in real time. [Source: Perspectium](https://www.perspectium.com/blog/configuring-a-servicenow-real-time-dashboard/) + +### Handling ServiceNow's Tabular Data Structure + +ServiceNow returns records as JSON arrays keyed to table field names. When building outside the native ServiceNow UI, state classes parse those arrays into dictionaries, apply filters by ticket state or priority, and pass results to table components that support pagination, sorting, and row selection for drill-down workflows. For advanced table features, [AG Grid](https://reflex.dev/blog/using-ag-grid-in-reflex/) offers enterprise-grade capabilities. Because incidents change state and tickets get reassigned constantly, a WebSocket connection can push those updates to every connected user without requiring the browser to poll on a fixed interval, keeping displayed metrics accurate without unnecessary API overhead. For long-running data syncs, consider [background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) to handle async operations. + +## Deploying Your ServiceNow Dashboard to Production + +Packaging a completed dashboard for production involves more than just shipping code. ServiceNow connections carry authentication credentials, role-based access logic, and data transformation layers that all need to travel together cleanly. + +Multi-region support keeps latency low for IT teams spread across global offices, and CI/CD integration with GitHub Actions means new ServiceNow metrics or updated filters ship automatically on merge. [Reflex hosting](https://reflex.dev/hosting/) provides single-command deployment with built-in scaling. + +[Organizations integrate ServiceNow with third-party solutions](https://www.perspectium.com/blog/servicenow-dashboards/) to overcome native dashboard limitations, often adding separate BI tools just to get external data views. A well-structured Python application can replace that stack by handling data retrieval, transformation, and visualization without a separate BI layer sitting in between. + +For enterprise teams with sensitive ITSM data, VPC and on-premises deployment keep ServiceNow credentials entirely within controlled infrastructure. Nothing touches a public cloud unless you choose it. + +### Production Considerations for IT Operations Dashboards + +ServiceNow dashboards need access boundaries that match your organization's existing RBAC policies. Role-based access can be implemented through Python logic, checking user permissions before exposing incident records or change workflows. Key areas to account for before go-live include: + +- Credential management so ServiceNow API tokens are stored in environment variables, never hardcoded into application logic. + +- RBAC enforcement at the data layer so users only see records their ServiceNow roles permit. + +- Audit logging for dashboard queries, which matters for compliance in industries with strict oversight. + +- Graceful error handling when ServiceNow API rate limits or token expirations occur mid-session. + +## FAQ + +### Can I build a ServiceNow dashboard without JavaScript? + +Yes. Reflex lets you build complete ServiceNow dashboards in pure Python, including API calls, data transformation, and UI components, without writing any JavaScript. + +### ServiceNow native dashboards vs Reflex dashboards? + +ServiceNow native dashboards require licensed user access and limit interactivity for external stakeholders. Reflex dashboards connect to ServiceNow's REST API and provide live, interactive views that anyone can access without an ITSM license, while supporting custom logic and third-party data merging. + +### How do I connect ServiceNow APIs to my Reflex app? + +Install the ServiceNow API SDK via pip, configure your instance URL and authentication tokens at the project level, then write event handlers in your Reflex state class that fetch incident records or change requests directly. Reflex's backend handles all API calls server-side with credentials never exposed to the browser. + +### What components do ServiceNow dashboards need? + +Most ServiceNow dashboards use stat cards for metrics like open ticket counts and SLA compliance, sortable data tables for incident lists with priority filters, time-series charts for trend analysis, and filter controls for status categories and assignment groups. Reflex provides these as built-in components. + +### When should I deploy a custom ServiceNow dashboard instead of using native reports? + +If stakeholders without ServiceNow licenses need live data access, if you're merging ITSM data with external monitoring tools like Datadog, or if native dashboard limitations block the custom prioritization logic your team requires, a Reflex dashboard gives you the flexibility without BI tooling overhead. diff --git a/blog/build-dashboard-twilio-python.md b/blog/build-dashboard-twilio-python.md new file mode 100644 index 000000000..6e4282d5b --- /dev/null +++ b/blog/build-dashboard-twilio-python.md @@ -0,0 +1,152 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Twilio in 2026" +title_tag: "Build Twilio Dashboard in Python (April 2026)" +description: "Learn how to build a Twilio dashboard with Python in April 2026. Track SMS delivery, call analytics, and costs without frontend handoffs." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Twilio dashboard Python, SMS dashboard, Twilio API metrics, messaging analytics Python, Twilio monitoring, communication dashboard" + } +] +faq: [ + {"question": "Can I build a Twilio dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full Twilio integrations entirely in Python, including the UI, API logic, and webhook handlers. The Twilio Python SDK works natively in Reflex's FastAPI backend, so there's no JavaScript layer required."}, + {"question": "What's the fastest way to connect Twilio APIs to a production dashboard?", "answer": "Install the Twilio Python SDK via pip, set your Account SID and Auth Token at the project level, and call Twilio APIs directly inside Reflex state classes or event handlers. Webhook callbacks route into Reflex API routes in the same codebase, so you deploy everything together with `reflex deploy`."}, + {"question": "How do I handle real-time Twilio webhook updates in a dashboard?", "answer": "Incoming Twilio webhook events (delivery receipts, status callbacks, error notifications) update Python state directly through Reflex API routes. Computed vars recalculate aggregated metrics automatically when state changes, and the UI reflects updates without polling logic or manual refresh triggers."}, + {"question": "Reflex vs Streamlit for building Twilio monitoring tools?", "answer": "Reflex gives you full control over the UI with 60+ built-in components and event-driven state management, while Streamlit's script rerun model causes performance issues under load and lacks built-in webhook handling. For production Twilio dashboards with custom layouts and real-time updates, Reflex is the better fit."}, + {"question": "How does Reflex handle Twilio credential management across multiple dashboards?", "answer": "Reflex allows you to set your Twilio Account SID and Auth Token once at the project level, and every application within that project inherits the connection automatically. This eliminates repetitive per-app credential setup and reduces the risk of misconfiguration across multiple Twilio-connected dashboards."}, + {"question": "Can I use AG Grid for displaying Twilio message data in Reflex?", "answer": "Yes. AG Grid wraps cleanly into Reflex's Python codebase for operations teams that need advanced features like column pinning, multi-filter logic, or bulk selection when displaying Twilio message records. This works without writing any JavaScript."}, + {"question": "What types of Twilio dashboards can I build with Reflex?", "answer": "Common Twilio dashboards include SMS delivery monitoring, voice call analytics with duration and drop rates, messaging compliance tracking, API cost visibility broken down by channel, and real-time conversation metrics showing live message volume and error patterns."}, + {"question": "Does Reflex support multi-region deployment for Twilio webhooks?", "answer": "Yes. Reflex Cloud's multi-region infrastructure keeps webhook endpoints responsive regardless of traffic origin, which is important because Twilio's webhook callbacks operate on strict response timeouts where latency matters."}, + {"question": "How do I validate Twilio webhook signatures in a Reflex app?", "answer": "Before going live, you should register your production webhook URLs inside the Twilio Console and verify that signature validation is active to block spoofed requests. This security measure ensures that incoming webhook events are actually from Twilio."}, + {"question": "Can I customize visualizations beyond Reflex's built-in components?", "answer": "Yes. If a specific visualization isn't available in Reflex's 60+ built-in UI elements, you can wrap any React component directly in Python, so the framework never becomes a ceiling on what you can build."}, + {"question": "What happens when Twilio updates their API and I need to change my dashboard?", "answer": "Since the entire dashboard is in Python using the Twilio Python SDK, your team makes the change in Python and the dashboard reflects it automatically. There's no need to coordinate between backend and frontend teams or understand generated JavaScript code."}, + {"question": "How should I handle sensitive customer message data in my Twilio dashboard?", "answer": "For teams handling sensitive customer communication data, Reflex supports self-hosted and VPC deployment options that keep credentials and message records inside your own infrastructure while maintaining webhook URL registration and credential rotation in the same Python codebase."}, + {"question": "What should I test before deploying a Twilio dashboard to production?", "answer": "Run a load test against your SMS and call volume peaks to confirm your polling intervals and state updates won't bottleneck under real traffic conditions. Also set up health check endpoints so your hosting layer can detect and restart unresponsive webhook handlers automatically."}, + {"question": "How does Reflex's state management help with complex Twilio dashboards?", "answer": "Reflex's state-driven architecture keeps complex dashboards organized as you add cascading filters, multi-page views, and real-time message counters. State is defined in Python classes with event handlers that respond to user actions cleanly, without callback sprawl to manage."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Reflex lets you build Twilio dashboards entirely in Python, connecting SMS delivery, call analytics, and cost tracking without frontend handoffs + +- State management handles real-time webhook updates automatically. No polling logic or manual refresh triggers required + +- Deploy webhooks and UI together with one command; VPC options keep customer message data inside your infrastructure + +- Reflex is a full-stack Python framework that outputs readable code your team can maintain, used by 40% of Fortune 500 companies + +## What You Can Build: Twilio Dashboard Overview + +Twilio generates a lot of data. Every SMS sent, every call routed, every failed delivery leaves a trace in the API. The challenge for operations teams and support managers is turning that trace into something actionable, fast. + +With Reflex and Twilio's APIs, you can build dashboards that surface exactly what those teams need. A few common builds worth knowing about, and you can find more inspiration in [Reflex templates](https://reflex.dev/templates/): + +- SMS delivery monitoring: track sent, delivered, failed, and undelivered message rates across campaigns or customer segments + +- Voice call analytics: visualize call durations, drop rates, and queue wait times across your contact center + +- Messaging compliance tracking: flag errors, unsubscribes, and carrier filtering events for compliance officers + +- API cost visibility: break down Twilio spend by channel (SMS, WhatsApp, voice) so engineering and finance teams stay aligned + +- Real-time conversation metrics: show live message volume, response rates, and error patterns as they happen + +Twilio's Messaging Insights already provides real-time performance reports with delivery, error, and conversion data. A Reflex dashboard pulls that into a UI your team actually controls, with filtering, drill-downs, and layout tuned to how your ops team works instead of how Twilio's console is designed. This approach to [building Python admin panels](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) keeps your tools under your control. + +Reflex's component library covers charts, tables, and live data display natively in Python, so you're not stitching together separate frontend tools to make this work. + +## Why Python Developers Choose Reflex for Twilio Dashboards + +Python teams building Twilio integrations already write their message-sending, webhook-parsing, and API logic in the Twilio Python SDK. Reflex extends that same workflow into the frontend, so the entire stack stays in one language. No JavaScript. No React. No handoff between a backend Python engineer and a frontend developer who has to re-learn your Twilio data model. + +That matters practically. When Twilio updates an API endpoint or adds a new compliance field, your team makes the change in Python and the dashboard reflects it. With code-generation tools that output JavaScript, the same change requires understanding a codebase that nobody on your data or backend team actually owns. Reflex's output is readable, auditable Python that domain experts can trace and fix without frontend expertise. + +There are a few specific reasons Python teams keep coming back to Reflex for Twilio work: + +- The [state-driven architecture](https://reflex.dev/blog/reflex-architecture/) keeps complex dashboards organized as you add cascading filters, multi-page views, and real-time message counters. State stays defined in Python classes with event handlers that respond to user actions cleanly, with no callback sprawl to manage. + +- Reflex ships 60+ built-in UI elements covering charts, tables, and filter interfaces that Twilio dashboards rely on directly out of the box. + +- If a specific visualization is not available, you can [wrap any React component](https://reflex.dev/blog/custom-components/) directly in Python, so the framework never becomes a ceiling on what you can build. + +## Connecting Twilio to Your Reflex App + +Twilio's REST APIs follow consistent patterns across products, whether you're working with the Messaging API, Voice, or Verify. That consistency makes the [Twilio Python SDK](https://www.twilio.com/docs/usage/api) a natural fit for Reflex's backend layer. + +Because Reflex compiles to a FastAPI backend with full PyPI compatibility, installing the official Twilio SDK is a single `pip install`. From there, any Twilio API call lives directly inside a Python state class or event handler. No separate microservice. No middleware layer sitting between your frontend and your Twilio credentials. The Reflex app is the backend. + +Credential management works at the project level. You set your Twilio Account SID and Auth Token once, and every application within that project inherits the connection automatically. For teams running multiple Twilio-connected dashboards, this eliminates the repetitive per-app credential setup that otherwise creates drift and misconfiguration over time. + +Webhook handling fits naturally into the same layer. Incoming delivery receipts, status callbacks, and error events from Twilio route directly into Reflex API routes and update state in Python. Outbound calls and inbound webhooks live in the same codebase, managed with the same patterns your team already knows. + +## Key Dashboard Components for Twilio Data + +Building a useful Twilio dashboard comes down to picking the right components for the right data. Each Twilio API endpoint returns structured data that maps naturally to specific UI components, so the choices you make here directly affect how readable and actionable your dashboard becomes. + +### Message Tables and Delivery Status + +Twilio's Messages API returns structured records: message SID, direction, status, timestamps, and error codes. Built-in table components render these with sorting, filtering, and pagination handled in Python state. For operations teams that need column pinning, multi-filter logic, or bulk selection, [AG Grid](https://reflex.dev/blog/using-ag-grid-in-reflex/) wraps cleanly into the same Python codebase without touching JavaScript. + +### Real-Time Metrics and Charts + +> + +Twilio recommends using Twilio Sync to power real-time dashboards, populating data in Sync maps based on TaskRouter event stream updates. + +Incoming webhook events update Python state directly, and computed vars recalculate aggregated metrics automatically each time state changes. No polling logic. No manual UI refresh triggers. [Plotly and Recharts](https://reflex.dev/blog/top-10-data-visualization-libraries/) both wrap in pure Python for time-series and breakdown views. + +| Dashboard Element | Twilio Data Source | Reflex Component | +|---|---|---| +| Message log table | Messages API list endpoint | rx.table or AG Grid | +| Delivery rate chart | Webhook status callbacks | Plotly line chart (wrapped) | +| Error breakdown | Error codes from message status | rx.recharts bar chart | +| Real-time alert feed | Webhook event stream | rx.list with live updates | +| Cost summary cards | Message pricing by channel | rx.stat or rx.card | + +## Deploying Your Twilio Dashboard to Production + +Shipping a Twilio dashboard with Reflex means one deployment pipeline covers everything: webhook handlers, credential management, background polling jobs, and the UI itself. There's no separate frontend build step because there's no separate frontend. + +Twilio's webhook callbacks operate on strict response timeouts, so latency matters. [Reflex Cloud's multi-region infrastructure](https://reflex.dev/hosting/) keeps those endpoints responsive regardless of where your traffic originates. When Twilio updates an API schema or new compliance rules require dashboard changes, CI/CD hooks for GitHub Actions and GitLab CI trigger automated redeployments without manual intervention. + +For teams handling sensitive customer communication data, [self-hosted and VPC deployment](https://reflex.dev/blog/self-hosting-reflex-with-docker/) keeps credentials and message records inside your own infrastructure while the app configuration handles webhook URL registration and credential rotation in the same Python codebase your team already owns. + +### Deployment Checklist Before Going Live + +Before pushing to production, confirm the following are in place: + +- Store all Twilio credentials as environment variables, never hardcoded, so credential rotation doesn't require code changes. + +- Register your production webhook URLs inside the Twilio Console and verify signature validation is active to block spoofed requests. Follow [Twilio webhook best practices](https://hookdeck.com/webhooks/platforms/twilio-webhooks-features-and-best-practices-guide) for secure implementation. + +- Set up health check endpoints so your hosting layer can detect and restart unresponsive webhook handlers automatically. + +- Run a load test against your SMS and call volume peaks to confirm your polling intervals and state updates won't bottleneck under real traffic conditions. + +## FAQ + +### Can I build a Twilio dashboard without JavaScript? + +Yes. Reflex lets you build full Twilio integrations entirely in Python, including the UI, API logic, and webhook handlers. The Twilio Python SDK works natively in Reflex's FastAPI backend, so there's no JavaScript layer required. + +### What's the fastest way to connect Twilio APIs to a production dashboard? + +Install the Twilio Python SDK via pip, set your Account SID and Auth Token at the project level, and call Twilio APIs directly inside Reflex state classes or event handlers. Webhook callbacks route into Reflex API routes in the same codebase, so you deploy everything together with `reflex deploy`. + +### How do I handle real-time Twilio webhook updates in a dashboard? + +Incoming Twilio webhook events (delivery receipts, status callbacks, error notifications) update Python state directly through Reflex API routes. Computed vars recalculate aggregated metrics automatically when state changes, and the UI reflects updates without polling logic or manual refresh triggers. + +### Reflex vs Streamlit for building Twilio monitoring tools? + +Reflex gives you full control over the UI with 60+ built-in components and event-driven state management, while Streamlit's script rerun model causes performance issues under load and lacks built-in webhook handling. For production Twilio dashboards with custom layouts and real-time updates, Reflex is the better fit. diff --git a/blog/build-dashboard-with-anthropic.md b/blog/build-dashboard-with-anthropic.md new file mode 100644 index 000000000..6feda3da8 --- /dev/null +++ b/blog/build-dashboard-with-anthropic.md @@ -0,0 +1,139 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Anthropic in 2026" +title_tag: "Build Anthropic Dashboard 2026" +description: "Learn how to build a dashboard with Anthropic in April 2026. Track token usage, model costs, and streaming responses using Python and Reflex." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Anthropic dashboard Python, Claude dashboard, Claude API metrics, AI usage dashboard, Anthropic analytics Python" + } +] +faq: [ + {"question": "Can I build a dashboard with Anthropic without JavaScript?", "answer": "Yes. Reflex lets you build full Anthropic dashboards entirely in Python, with the Anthropic SDK installing directly via pip and API calls living inside state classes. The framework's WebSocket architecture handles streaming Claude responses natively, pushing each token to the UI as it arrives without any frontend JavaScript required."}, + {"question": "Anthropic dashboard Reflex vs Streamlit?", "answer": "Reflex handles Claude's streaming responses natively through WebSocket-based state sync and event handlers with yield statements, while Streamlit's script rerun model re-executes your entire file on every interaction, breaking streaming flows and causing memory leaks. Reflex also persists multi-turn conversation state automatically through Python classes, eliminating the manual session management that makes Streamlit unreliable for production Claude integrations."}, + {"question": "What's the fastest way to ship an Anthropic dashboard in 2026?", "answer": "Install the Anthropic Python SDK into a Reflex project, configure your API key once at the project level, and build your dashboard with state classes that handle Claude API calls. Deployment takes a single `reflex deploy` command with no separate backend to configure, letting Python teams ship production dashboards in hours rather than weeks of React boilerplate."}, + {"question": "How do I track Claude token usage across multiple models?", "answer": "Use Claude's Token Counting API to calculate usage before requests fire, then store per-request metadata in your Reflex state class. Build token usage tables with computed vars that automatically sum totals across Claude Opus 4.6, Sonnet 4.6, and Haiku 4.5, updating the UI in real-time as your cost breakdown cards recalculate without client-side JavaScript."}, + {"question": "How does Reflex handle streaming responses from Claude's API?", "answer": "Reflex uses WebSocket architecture with event handlers that support yield statements, allowing you to push incremental state updates to the browser as each token arrives from Claude. This eliminates the need for polling and handles server-sent events natively without any JavaScript required."}, + {"question": "What are the main use cases for Anthropic dashboards in production?", "answer": "Common use cases include real-time conversation analytics tracking token usage and response latency, LLM cost monitoring with breakdowns by model tier, AI agent performance dashboards measuring task completion rates and tool calls, and multi-model comparison interfaces for A/B testing prompts across Claude Opus, Sonnet, and Haiku."}, + {"question": "Can I deploy an Anthropic dashboard in a VPC for compliance requirements?", "answer": "Yes. Reflex supports self-hosted deployments with VPC isolation, keeping Claude conversation data inside your own infrastructure without any code changes. The same Python codebase that runs locally deploys to air-gapped environments, which is essential for handling sensitive LLM outputs in regulated industries."}, + {"question": "How does project-level integration work for Anthropic credentials?", "answer": "Project-level integration configuration lets you set your Anthropic API credentials once across your workspace, and every dashboard application in that project shares them automatically. This eliminates per-app reconfiguration and keeps credentials centralized in environment variables that persist across multi-region deployments."}, + {"question": "What's the benefit of using Claude's Token Counting API in a dashboard?", "answer": "The Token Counting API lets you calculate token usage before a request fires, enabling cost forecasting and allowing you to gate expensive Claude Opus calls behind pre-flight checks. You can surface projected costs directly in your dashboard UI before execution, which matters when running models at scale."}, + {"question": "How do I persist conversation history across multiple turns with Claude?", "answer": "Store conversation history in a typed Python list on your Reflex state class, which automatically persists across interactions without manual session management. The state class maintains multi-turn context naturally, and Reflex's architecture handles this through Python classes and event handlers without additional middleware."}, + {"question": "What cost savings are available with Claude's Message Batches API?", "answer": "The Message Batches API cuts costs by 50% for high-volume batch workloads and pairs naturally with Reflex's background task pattern. Both Claude Opus 4.6 and Sonnet 4.6 support 300k max output tokens on this API, making it ideal for large structured data tasks that can be processed asynchronously."}, + {"question": "How do I build real-time cost breakdown cards for different Claude models?", "answer": "Use computed vars in Reflex state to calculate derived metrics server-side based on per-request pricing data, with Claude Opus 4.6 at $5 input / $25 output per million tokens. When users filter by model or date range, the totals recalculate automatically without client-side JavaScript, updating the UI in real-time."}, + {"question": "Can I automate deployment of my Anthropic dashboard with CI/CD?", "answer": "Yes. Reflex integrates with GitHub Actions to automate deployment on every merge while keeping Anthropic credentials out of version control. The Reflex config API manages environment-specific settings cleanly, so staging and production can point to different API keys without manual switching."}, + {"question": "How do I track prompt caching performance in my Claude dashboard?", "answer": "Build a cache hit rate card using your request logs, since Claude's API supports caching with a default 5-minute lifetime (extendable to 1 hour). This dashboard component immediately shows whether your system prompt architecture is saving money through cache hits or burning tokens on every call."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build live Claude dashboards in pure Python tracking token usage, model costs, and streaming responses without JavaScript + +- Reflex handles Anthropic's streaming API natively via WebSocket state sync, avoiding Streamlit's script rerun problems + +- Project-level integration shares Anthropic credentials across all apps automatically, eliminating per-dashboard configuration + +- Deploy to production with VPC isolation keeping Claude conversation data in your infrastructure for compliance requirements + +- Reflex is an open-source Python framework for building full-stack web apps, used by 40% of Fortune 500 companies + +## What You Can Build: Anthropic Dashboard Overview + +Building a dashboard with Anthropic is less about visualization and more about control. When your product runs on Claude, you need visibility into what's actually happening, and a well-built dashboard gives your team exactly that. + +Here's what Python teams typically ship: + +- Real-time conversation analytics showing token usage, response latency, and session patterns across your user base + +- LLM cost monitoring that tracks spend by model tier, with breakdowns between Claude Opus 4.6 for complex reasoning tasks and Sonnet 4.6 for production-volume workloads + +- AI agent performance dashboards measuring task completion rates, tool call frequency, and failure patterns over time + +- Multi-model comparison interfaces that let engineers A/B test prompts or swap between Claude Haiku 4.5 and Sonnet 4.6 without touching production + +The Anthropic-specific data worth surfacing depends heavily on your architecture. If you're running batch jobs, Claude Opus 4.6 and Sonnet 4.6 both support 300k max output tokens on the Message Batches API, which makes large structured data tasks far more tractable. Tracking batch job status and output volume in a live dashboard beats parsing logs manually. + +With WebSocket-based state sync, streaming Claude responses into a [live UI](https://reflex.dev/templates/chat-bot/) is straightforward, handling real-time data flow without polling hacks. + +## Why Python Developers Choose Reflex for Anthropic Dashboards + +Python developers building Anthropic dashboards have a clear path with Reflex: the Anthropic Python SDK installs via pip, requires Python 3.9+, and drops directly into a Reflex project with no adapter layer. Your Claude API calls live inside Reflex state classes alongside your app logic, keeping everything in one place instead of split across a separate backend and frontend. + +That architectural difference carries real weight. Anthropic's API supports server-sent events for incremental streaming, with the Python SDK offering multiple streaming modes out of the box. Reflex's WebSocket architecture handles those streaming responses natively, pushing each token to the UI as it arrives. Multi-turn conversation state persists across interactions without manual session wrangling. + +The alternatives fall short in meaningful ways: + +- [Streamlit's script rerun model](https://reflex.dev/blog/reflex-streamlit/) re-executes your entire file on every user interaction, which breaks streaming flows entirely and creates memory leaks that SellerX's Head of AI described as "super inefficient." + +- React gives you streaming support, but only after building and deploying a separate backend to host your Claude calls, adding extra overhead before you can ship anything. + +With Reflex, [state management works through Python classes](https://reflex.dev/blog/reflex-architecture/) and event handlers. You define your conversation history, token counters, and model selection variables as typed Python attributes. When a user submits a prompt, an event handler fires your Claude API call, yields state updates mid-stream, and the UI reflects each change live. No polling, no JavaScript required. + +## Connecting Anthropic to Your Reflex App + +Reflex's backend state pattern removes the middleware problem entirely. There's no Express server to spin up, no Flask route to wire. The Anthropic Python SDK installs via pip directly into your project, and your Claude API calls live inside state classes alongside the rest of your app logic. Project-level integration configuration means you set your Anthropic credentials once across your workspace, and every dashboard application in that project shares them automatically, no per-app reconfiguration needed. + +| Integration Aspect | Configuration Approach | Benefit | +|---|---|---| +| API Authentication | Environment variables via Reflex config | Centralized credential management | +| Streaming Responses | Event handlers with yield statements | Real-time UI updates without polling | +| Conversation State | Python state classes with message lists | Multi-turn context persistence | +| Token Management | Pre-request counting via Token API | Cost forecasting before execution | + +Claude's [Token Counting API](https://platform.claude.com/docs/en/api/overview) lets you calculate token usage before a request fires, which matters when you're running Claude Opus 4.6 at scale. You can gate expensive calls behind a pre-flight check and surface projected costs directly in your dashboard UI. For high-volume batch workloads, the [Message Batches API](https://pypi.org/project/anthropic/) cuts costs by 50% and pairs naturally with Reflex's background task pattern, processing large jobs asynchronously while keeping the UI responsive. + +Streaming is where Reflex's event handler model earns its keep. Yield statements mid-handler push incremental state updates to the browser over WebSocket as each token arrives from Claude. Conversation history stays in a typed Python list on your state class, persisting across turns without manual session management. + +## Key Dashboard Components for Anthropic Data + +Each piece of the Claude API response has a natural UI counterpart, and the table below maps the most common ones to their Reflex implementations: + +| Dashboard Component | Claude Data Type | Reflex Implementation | +|---|---|---| +| Streaming Response Display | Server-sent events | rx.text_area with yield updates | +| Token Usage Table | API response metadata | rx.data_table with computed totals | +| Model Comparison Chart | Multi-model request logs | rx.recharts with state-driven data | +| Cost Breakdown Cards | Per-request pricing calculation | rx.stat with calculated state vars | +| Conversation History | Message array | rx.foreach over state message list | + +Pricing visibility matters more now that Claude Opus 4.6 runs at $5 input / $25 output per million tokens, a [66.7% reduction](https://www.anthropic.com/pricing) versus the legacy Opus 4 baseline. [Cost breakdown cards](https://reflex.dev/use-cases/finance/) can surface per-conversation spend in real time, with computed vars in Reflex state calculating those metrics server-side, no client-side JavaScript required. When a user filters by model or date range, the totals recalculate automatically. + +Prompt caching is worth surfacing too. Claude's API supports caching with a default 5-minute lifetime, extendable to 1 hour for repeated long prompts. A cache hit rate card built from your request logs tells you immediately whether your system prompt architecture is saving money or burning tokens on every call. + +For model comparison charts, you pull request logs across Claude Opus 4.6, Sonnet 4.6, and Haiku 4.5 into Recharts components driven by Reflex state. Switching the date range or model filter fires an event handler, updates the state, and the chart redraws without a page reload or a separate API endpoint to manage. + +## Deploying Your Anthropic Dashboard to Production + +[Deploying your Anthropic dashboard](https://reflex.dev/hosting/) involves packaging your full Python application, Anthropic SDK dependencies, and all connection logic into a single deployable unit. No separate frontend pipeline, no backend server to configure independently. Reflex Cloud handles infrastructure provisioning, and your API keys stay in centralized environment variables that persist across multi-region deployments. + +For teams with [stricter requirements](https://reflex.dev/use-cases/consulting/), the compliance story is straightforward. Self-hosted deployments and VPC isolation keep Claude conversation data inside your own infrastructure without any changes to application code. The same Python codebase that runs locally deploys to an air-gapped environment, which matters when handling sensitive LLM outputs in compliance-focused industries. + +CI/CD integration with GitHub Actions automates deployment on every merge while keeping Anthropic credentials out of version control entirely. The Reflex config API manages environment-specific settings cleanly, so staging and production point to different API keys with no manual switching. [Project-level integration configuration](https://reflex.dev/blog/reflex-databricks-partnership/) means credentials set once propagate automatically across every dashboard in your workspace, removing the per-app credential work that slows teams down at scale. + +## FAQ + +### Can I build a dashboard with Anthropic without JavaScript? + +Yes. Reflex lets you build full Anthropic dashboards entirely in Python, with the Anthropic SDK installing directly via pip and API calls living inside state classes. The framework's WebSocket architecture handles streaming Claude responses natively, pushing each token to the UI as it arrives without any frontend JavaScript required. + +### Anthropic dashboard Reflex vs Streamlit? + +Reflex handles Claude's streaming responses natively through WebSocket-based state sync and event handlers with yield statements, while Streamlit's script rerun model re-executes your entire file on every interaction, breaking streaming flows and causing memory leaks. Reflex also persists multi-turn conversation state automatically through Python classes, eliminating the manual session management that makes Streamlit unreliable for production Claude integrations. + +### What's the fastest way to ship an Anthropic dashboard in 2026? + +Install the Anthropic Python SDK into a Reflex project, configure your API key once at the project level, and build your dashboard with state classes that handle Claude API calls. Deployment takes a single `reflex deploy` command with no separate backend to configure, letting Python teams ship production dashboards in hours instead of weeks of React boilerplate. + +### How do I track Claude token usage across multiple models? + +Use Claude's Token Counting API to calculate usage before requests fire, then store per-request metadata in your Reflex state class. Build token usage tables with computed vars that automatically sum totals across Claude Opus 4.6, Sonnet 4.6, and Haiku 4.5, updating the UI in real-time as your cost breakdown cards recalculate without client-side JavaScript. diff --git a/blog/build-dashboard-with-auth0.md b/blog/build-dashboard-with-auth0.md new file mode 100644 index 000000000..9165d1f66 --- /dev/null +++ b/blog/build-dashboard-with-auth0.md @@ -0,0 +1,167 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Auth0 in 2026" +title_tag: "Build Auth0 Dashboard Python Guide 2026" +description: "Learn how to build a custom Auth0 dashboard in Python for monitoring login patterns, security events, and user metrics. Complete guide for April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Auth0 dashboard Python, Auth0 analytics, authentication dashboard, Auth0 metrics Python, login monitoring dashboard" + } +] +faq: [ + {"question": "Can I build an Auth0 dashboard without JavaScript?", "answer": "Yes. Reflex lets you build complete Auth0 monitoring dashboards in pure Python, handling both the data layer and UI without requiring any JavaScript knowledge. The Auth0 Python SDK integrates directly into Reflex's backend, and all state management, API calls, and UI rendering happen in a single Python codebase that security engineers and data teams can read and modify."}, + {"question": "Auth0 dashboard Reflex vs Retool?", "answer": "Reflex gives you full control over the UI and outputs readable Python code that your team can debug and extend, while Retool locks you into a proprietary interface with rigid component constraints. When your authentication monitoring requirements get specific or you need to troubleshoot an issue at 2 AM, Reflex lets you read exactly what the application does in Python rather than reverse-engineering a no-code configuration."}, + {"question": "What's the best way to visualize Auth0 authentication trends?", "answer": "Reflex's Recharts integration covers standard Auth0 visualization patterns: line charts for login volume over time, bar charts for failed login attempts, pie charts for authentication method distribution, and area charts for user growth trends. All chart components work directly with Auth0 API data stored in Python state classes, with automatic re-rendering when your data refreshes."}, + {"question": "How do I deploy an Auth0 dashboard to production with Reflex?", "answer": "Run `reflex deploy` to package your Python backend, state management, and frontend into a single deployment. VPC deployment keeps Auth0 credentials inside your security perimeter, while CI/CD integration through GitHub Actions or GitLab CI supports scheduled metrics refresh, event-driven updates, and zero-downtime monitoring updates for security-critical dashboards."}, + {"question": "What Auth0 data can I monitor in a Reflex dashboard?", "answer": "You can monitor user records, authentication logs, and security events from Auth0's Management API. Common monitoring patterns include login success and failure rates, suspicious activity, user growth and churn, real-time access control patterns by role or region, and password reset frequency for audit purposes."}, + {"question": "Does Reflex support real-time Auth0 event monitoring?", "answer": "Yes. Reflex's background jobs can ingest live authentication events from Auth0's log streaming endpoints without blocking the main event loop, while WebSocket-based state sync pushes updates to your dashboard components in real-time."}, + {"question": "How does Reflex handle Auth0 API credentials securely?", "answer": "API credentials stay server-side inside your Python state class rather than leaking into a JavaScript bundle. For production deployments, VPC support keeps Auth0 credential handling inside your security perimeter, and self-hosted Helm chart deployment means authentication log processing never leaves organizational boundaries."}, + {"question": "Can I use Auth0's Management API with any Python library in Reflex?", "answer": "Yes. The Auth0 Python SDK and any PyPI-compatible library works natively in Reflex's backend with no adapter layer required, plugging directly into event handlers to fetch user lists, query authentication logs, or pull security event data."}, + {"question": "What components does Reflex provide for building dashboards?", "answer": "Reflex ships 60+ built-in components including data tables for paginated user lists with sorting and filtering, line and bar charts for trend visualization, stat cards for real-time metrics, and React component wrapping for specialized visualizations that fall outside native coverage."}, + {"question": "How do I share Auth0 credentials across multiple dashboards?", "answer": "Reflex's project-level integration configuration lets you set Auth0 credentials once, and they're shared across every dashboard application in that project. Tenant URLs, API tokens, and client secrets live in one place, eliminating per-app reconfiguration."}, + {"question": "Can I filter and sort Auth0 data without making additional API calls?", "answer": "Yes. Once Auth0 API responses are loaded into Reflex state, the data table component handles sorting, filtering, and pagination entirely client-side, allowing security teams to drill into failed login attempts or filter users by connection type without round-tripping to Auth0."}, + {"question": "What's the advantage of using computed vars for Auth0 metrics?", "answer": "Computed vars calculate derived values like authentication success rate or top failure reasons directly in Python state classes, recalculating automatically when underlying data refreshes and re-rendering only the components that display changed metrics, avoiding manual aggregation logic."}, + {"question": "How does Reflex handle Auth0 dashboards differently than code generation tools?", "answer": "Reflex outputs readable Python code that your team can debug and extend, while code generation tools produce minified JavaScript bundles that are difficult to troubleshoot. This means you can read exactly what the application does in Python rather than reverse-engineering generated code, especially critical during production incidents."}, + {"question": "Can I build an Auth0 dashboard for multiple teams with different views?", "answer": "Yes. Project-level credentials shared across all dashboard apps in your Reflex workspace make it straightforward to spin up multiple monitoring views for different teams without reconfiguring Auth0 integration for each application, supporting different visualization requirements while maintaining centralized permission management."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Auth0 dashboards visualize login patterns, security events, and user metrics in real-time + +- Reflex handles Auth0 integration in pure Python using the Auth0 SDK without JavaScript + +- Project-level Auth0 credentials share across all dashboard apps in your Reflex workspace + +- Deploy with VPC support to keep authentication data inside your security perimeter + +- Reflex is a full-stack Python framework for building web apps with 28,000+ GitHub stars + +## What You Can Build: Auth0 Dashboard Overview + +Auth0 gives administrators a lot of control out of the box: [managing users, password resets, and event logs](https://www.getapp.com/security-software/a/auth0/). But the native Auth0 interface has limits. When security teams, DevOps engineers, or product analysts need a tailored view into their authentication data, they build [custom dashboards](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) that pull from Auth0's APIs. + +What does that look like in practice? A few common patterns: + +- Visualizing login success and failure rates over time to spot anomalies before they become incidents + +- Monitoring suspicious activity and flagged security events across your user base + +- Tracking user growth and churn across multiple Auth0 applications in a single view + +- Displaying real-time access control patterns broken down by role or region + +- Surfacing password reset frequency and anomalous session behavior for audit purposes + +[Activity analytics confirm implementation health](https://auth0.com/blog/auth0-levels-up-analytics-experience/). The focus here is read-only monitoring, not full provisioning workflows. That scope keeps the dashboard practical for security operations, DevOps, and product teams who need visibility without needing to rebuild Auth0's admin UI. + +Reflex handles both the data layer and the UI in pure Python, which means no React required and no separate backend to wire up. + +## Why Python Developers Choose Reflex for Auth0 Dashboards + +Building an Auth0 dashboard means choosing where your logic lives. With Reflex, the answer is simple: all of it stays in Python. + +Authentication monitoring logic, state management, and UI code share a single codebase that security engineers and data teams can read without switching contexts. [Auth0's Python SDK provides convenient API access](https://github.com/auth0/auth0-python), plugging directly into Reflex's backend since any PyPI-compatible library works natively. No adapter layer, no translation step between your data fetching and your UI. + +Contrast that with Retool or [similar low-code tools](https://reflex.dev/blog/internal-tool-builders/). You get a proprietary interface with rigid component constraints and limited escape hatches when your requirements get specific. Reflex ships 60+ built-in components covering the core dashboard primitives you actually need: + +- Data tables for paginated user lists, with sorting and filtering handled entirely in Python state + +- Line and bar charts for authentication trend visualization across configurable time windows + +- Stat cards for real-time security metrics surfaced at a glance without custom widget configuration + +- React component wrapping for any specialized visualization that falls outside what Reflex covers natively + +The debugging argument matters most at 2 AM when a login spike hits. With code generation tools, you're reverse-engineering minified JavaScript bundles under pressure. With Reflex, you open a Python file and read what the application actually does. That's the same skill set your security engineers and data teams already have. + +## Connecting Auth0 to Your Reflex App + +Getting Auth0 connected to Reflex starts with a single pip install of the [Auth0 Python library](https://github.com/auth0/auth0-python), which gives you direct access to Auth0's Management API from your backend code. + +### Project-Level Integration Configuration + +Reflex's project-level integration configuration means you set your Auth0 credentials once and they are shared across every dashboard application in that project. No per-app reconfiguration when you spin up a second monitoring view for a different team. Tenant URLs, API tokens, and client secrets live in one place, making permission management straightforward at scale. + +### Python SDK Integration + +Once installed, the Auth0 SDK plugs directly into Reflex's event handlers. You can call Management API endpoints to fetch user lists, query authentication logs, or pull security event data, then store the results in a Python state class. From there, Reflex's state system automatically pushes updated values to the UI. Critically, API credentials stay server-side inside your state class instead of leaking into a JavaScript bundle. + +### Authentication Data Flow + +For real-time feeds, Auth0's log streaming endpoints pair well with Reflex's [background jobs](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) to ingest live authentication events without blocking the main event loop. Computed vars then convert raw API responses into clean metrics your dashboard components can render directly, with no client-side processing required. + +## Key Dashboard Components for Auth0 Data + +Auth0 returns a few distinct data shapes: user records, authentication logs, and security events. Each maps to a different component type in Reflex. + +### Tables for User and Event Data + +The [data table component](https://reflex.dev/blog/using-ag-grid-in-reflex/) handles sorting, filtering, and pagination after loading Auth0 API responses into state. Security teams can drill into [failed login attempts](https://reflex.dev/blog/implementing-sign-in-with-google/) or filter users by connection type without additional API calls round-tripping to Auth0. + +### Charts for Authentication Trends + +Reflex's [Recharts integration](https://reflex.dev/blog/graphing-update/) covers every standard Auth0 visualization pattern without requiring D3.js expertise: + +| Auth0 Data Type | Visualization | Reflex Component | Use Case | +|---|---|---|---| +| Login volume over time | Line chart | recharts.LineChart | Track authentication patterns | +| Failed login attempts | Bar chart | recharts.BarChart | Security monitoring | +| Authentication methods | Pie chart | recharts.PieChart | Connection distribution | +| User growth trends | Area chart | recharts.AreaChart | Product analytics | + +### Real-Time Stat Cards + +Auth0 [handles 10 billion+ authentications every month](https://auth0.com), generating high-volume event streams worth surfacing as live metrics. Stat cards display active sessions, recent failed logins, or authentication response times, with Reflex's WebSocket-based state sync pushing updates from background jobs polling Auth0 APIs on intervals. + +### Computed Vars for Calculated Metrics + +Raw Auth0 event data needs aggregation before it becomes useful. Reflex's computed var pattern calculates values like authentication success rate or top failure reasons directly in Python state classes, recalculating automatically when underlying data refreshes and updating only the components that display changed metrics. + +## Deploying Your Auth0 Dashboard to Production + +Once your dashboard is ready, packaging the Python backend, state management, and frontend components into a [single deployment](https://reflex.dev/hosting/) removes the need for separate pipelines for frontend and backend. + +### Enterprise Security and Compliance + +VPC deployment keeps Auth0 credential handling inside your security perimeter. For air-gapped environments, self-hosted Helm chart deployment means [authentication log processing](https://reflex.dev/blog/microsoft-azure-authentication/) never leaves organizational boundaries. + +### CI/CD Integration for Monitoring Dashboards + +Different teams ship monitoring dashboards in different ways. The table below maps common deployment patterns to their Auth0 use cases so you can match your workflow to the right implementation. + +| Deployment Pattern | Implementation | Auth0 Use Case | +|---|---|---| +| Scheduled metrics refresh | GitHub Actions cron | Nightly authentication reports | +| Event-driven updates | GitLab CI webhooks | Security alert dashboards | +| Blue-green deployment | Helm chart rollout | Zero-downtime monitoring updates | + +Built-in alerting catches deployment failures before they affect security visibility, which matters when your dashboard is the first place your team looks during an incident. Getting this layer right means your Auth0 data stays accurate and accessible exactly when you need it most. + +## FAQ + +### Can I build an Auth0 dashboard without JavaScript? + +Yes. Reflex lets you build complete Auth0 monitoring dashboards in pure Python, handling both the data layer and UI without requiring any JavaScript knowledge. The Auth0 Python SDK integrates directly into Reflex's backend, and all state management, API calls, and UI code happen in a single Python codebase that security engineers and data teams can read and modify. + +### Auth0 dashboard Reflex vs Retool? + +Reflex gives you full control over the UI and outputs readable Python code that your team can debug and extend, while Retool locks you into a proprietary interface with rigid component constraints. When your authentication monitoring requirements get specific or you need to troubleshoot an issue at 2 AM, Reflex lets you read exactly what the application does in Python instead of reverse-engineering a no-code configuration. + +### What's the best way to visualize Auth0 authentication trends? + +Reflex's Recharts integration covers standard Auth0 visualization patterns: line charts for login volume over time, bar charts for failed login attempts, pie charts for authentication method distribution, and area charts for user growth trends. All chart components work directly with Auth0 API data stored in Python state classes, with automatic updates when your data refreshes. + +### How do I deploy an Auth0 dashboard to production with Reflex? + +Run `reflex deploy` to package your Python backend, state management, and frontend into a single deployment. VPC deployment keeps Auth0 credentials inside your security perimeter, while CI/CD integration through GitHub Actions or GitLab CI supports scheduled metrics refresh, event-driven updates, and zero-downtime monitoring updates for security-critical dashboards. diff --git a/blog/build-dashboard-with-database.md b/blog/build-dashboard-with-database.md new file mode 100644 index 000000000..89ba890e0 --- /dev/null +++ b/blog/build-dashboard-with-database.md @@ -0,0 +1,161 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With a Database in 2026" +title_tag: "Build a Database Dashboard in Python (April 2026)" +description: "Learn how to build a database dashboard in April 2026 with PostgreSQL, MongoDB, or Snowflake using Python. Complete tutorial for production-ready dashboards." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "database dashboard Python, SQL dashboard, database analytics Python, data dashboard tutorial, database monitoring Python" + } +] +faq: [ + {"question": "Can I build a database dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full database dashboards in pure Python, including queries, state management, and UI components, without writing any JavaScript. This works for PostgreSQL, MongoDB, MySQL, Snowflake, and any database with a Python connector."}, + {"question": "Reflex vs Streamlit for database dashboards?", "answer": "Reflex supports event-based state updates and server push, while Streamlit reruns the entire script on every interaction, causing memory leaks and slowdowns under load. Reflex also provides built-in auth, background jobs, and custom CSS control that Streamlit lacks, making it better for production database dashboards."}, + {"question": "How do I connect a PostgreSQL database to a Reflex dashboard?", "answer": "You connect using SQLAlchemy directly in your Reflex state class, just like a standard Python script. Database credentials are configured once at the project level and shared across all apps automatically. Queries run inside event handlers, and results update the UI instantly through Reflex's state sync."}, + {"question": "What's the best deployment option for a production database dashboard?", "answer": "Reflex Cloud handles infrastructure automatically with OpenTelemetry tracing and multi-region scaling, ideal for cloud databases. For regulated industries or private networks, self-hosted on-premises deployment keeps database traffic within your security perimeter with full VPC isolation and RBAC controls."}, + {"question": "When should I use a read replica instead of the production database?", "answer": "Switch to a read replica when heavy analytical queries during peak hours slow down your production application. Database dashboards with complex aggregations, reporting workloads, or high concurrent users should always point at read replicas to separate analytical load from transactional workloads."}, + {"question": "What types of dashboards can I build with a database in Reflex?", "answer": "You can build operational database monitoring dashboards that track query performance, connection pools, and replication lag, business intelligence dashboards for customer analytics and financial reporting, or real-time dashboards that stream live data updates. All three types can coexist in the same Reflex project using WebSocket-based state sync for real-time updates and background jobs for batch refreshes."}, + {"question": "Does Reflex require a data warehouse for database dashboards?", "answer": "No, Reflex lets you build dashboards that connect directly to your existing application database without requiring ETL infrastructure or a data warehouse first. This approach works well for operational monitoring and internal tools where you need live access to production or replica data."}, + {"question": "Which databases are supported by Reflex for dashboard development?", "answer": "Reflex natively supports PostgreSQL, MongoDB, MySQL, Snowflake, and Supabase through SQLAlchemy, pymongo, and native integrations. Any database with a Python connector available on PyPI works in Reflex, including Databricks, DuckDB, BigQuery, and ClickHouse."}, + {"question": "How does Reflex handle background tasks for database dashboards?", "answer": "Reflex includes a built-in background job system that runs heavy database queries asynchronously, keeping the UI responsive during long-running operations. This feature also handles scheduled batch refreshes during off-peak windows without requiring separate infrastructure."}, + {"question": "Can I use authentication and role-based access control in my database dashboard?", "answer": "Yes, Reflex ships with built-in authentication and RBAC controls that let you restrict which users can access specific data or dashboard features. Multi-user dashboards get access controls without requiring external middleware, and audit logging tracks every access event for compliance."}, + {"question": "What happens when database credentials change in my Reflex project?", "answer": "Database credentials and connection strings are configured once at the project level and automatically shared across every app in that project. When credentials change, you update them in one location and all dashboard apps inherit the new configuration without manual reconfiguration."}, + {"question": "How do I prevent dashboard queries from slowing down my production database?", "answer": "Connect your dashboard to a read replica instead of the production database to separate analytical workloads from transactional operations. Reflex also supports caching results, scheduling heavy queries during off-peak windows, and using background tasks to prevent blocking the UI during long-running queries."}, + {"question": "Can I wrap custom React components for database visualizations in Reflex?", "answer": "Yes, Reflex lets you wrap any React component when the 60+ built-in components don't cover your specific needs. For example, AG Grid wraps cleanly via Reflex's React component system for spreadsheet-level control in financial dashboards, while maintaining a pure Python development experience."}, + {"question": "What monitoring and observability features does Reflex provide for production dashboards?", "answer": "Reflex Cloud includes built-in OpenTelemetry distributed tracing and ClickHouse log aggregation that provide visibility into query latency, connection pool behavior, and user concurrency patterns. This observability works from day one without requiring custom configuration."}, + {"question": "How does Reflex handle real-time dashboard updates compared to polling?", "answer": "Reflex uses WebSocket-based state sync to push server state changes to the browser instantly, eliminating the need for polling. When backend state changes, every connected client automatically receives the update, making it ideal for live counters, notification badges, and streaming data feeds."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can connect PostgreSQL, MongoDB, Snowflake, or Supabase to Reflex dashboards using native Python libraries without middleware layers or API contracts. + +- Build monitoring, business intelligence, or real-time dashboards entirely in Python using state classes and 60+ built-in components for charts, tables, and filters. + +- Deploy database dashboards with single-command cloud hosting or on-premises for industries requiring VPC isolation and RBAC controls. + +- Reflex is a full-stack Python framework that lets you build production-grade web apps without JavaScript, used by 40% of Fortune 500 companies for internal tools. + +## What You Can Build: Database Dashboard Overview + +Database dashboards fall into a few distinct categories, and knowing which you're building shapes every decision that follows. Unlike traditional BI tools that require a data warehouse first, a direct database dashboard points straight at your existing application database and builds on live data. Many organizations start here before ever touching ETL infrastructure. + +### Database Monitoring Dashboards + +These track the health of the database itself. Think query performance, connection pool utilization, cache hit ratios, replication lag, table bloat, and vacuum activity. PostgreSQL monitoring alone spans instance information, lock analysis, WAL stats, and replication metrics. For a complete guide to key metrics, see [PostgreSQL monitoring best practices](https://www.percona.com/blog/key-metrics-and-tools-for-effective-postgresql-monitoring/). DBAs and backend engineers use these dashboards to catch degradation before users notice anything. + +### Business Intelligence Dashboards + +On the business side, dashboards pull application data to support decisions: customer analytics, transaction flows, inventory counts, financial reporting. A dashboard is only as good as the story it tells, and thoughtful design matters more in 2026 than ever since data without context just creates noise. Learn more about [dashboard design best practices](https://www.metabase.com/learn/metabase-basics/querying-and-dashboards/dashboards/bi-dashboard-best-practices) for effective KPI visualization. For financial reporting, a [Reflex dashboard](https://reflex.dev/templates/finance-dashboard/) template can accelerate development. These dashboards typically connect to read replicas and surface KPIs for operators, managers, and executives. + +### Real-Time vs Batch Update Patterns + +Real-time dashboards use streaming data pipelines instead of fixed-schedule refreshes, showing state as it changes. A [real-time sales dashboard](https://reflex.dev/templates/real-time-sales-dashboard/) shows how this pattern applies to business metrics. Batch dashboards poll on a schedule. Both patterns are achievable within the same project: WebSocket-based state sync handles live updates natively, while scheduled background jobs handle batch refreshes without requiring separate infrastructure for either. + +## Why Python Developers Choose Reflex for Database Dashboards + +Most Python developers working with databases want to query Postgres, process the results, and show them in a UI without spinning up a separate frontend project or handing off to a JavaScript engineer. Reflex keeps the entire stack in Python, so nothing about your mental model changes when you move from data logic to UI. + +### Single Python Codebase for Full Stack + +State classes in Reflex are just Python classes. You write a database query using SQLAlchemy, psycopg2, or pymongo, process the results in a method, and the UI updates automatically. No REST layer to wire up, no JSON serialization boilerplate, no separate frontend build step. The 60+ built-in components cover charts, tables, filters, and forms out of the box, and you can wrap any React component when you need something more specific. + +### Production-Ready Database Features + +Reflex ships with an ORM, migrations, background jobs, file uploads, and authentication with RBAC included. Heavy queries run as [background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) so the UI stays responsive. Multi-user dashboards get access controls without reaching for external middleware. + +### Code Understandability for Database Teams + +When a query returns unexpected results in production, your data engineer opens the Python file and reads exactly what's happening. No source maps, no minified bundles. Domain experts can fix problems without frontend expertise, which matters when the people who understand your data schema are not the same people who know JavaScript. + +## Connecting a Database to Your Reflex App + +Reflex's backend architecture makes database integration feel like writing a regular Python script. State classes are Python classes, event handlers are Python methods, and any library on PyPI drops in via `pip install`. There is no middleware layer to configure and no API contract to maintain between a frontend and a separate backend service. Your database query lives in the same file as your UI logic. + +### Database Connection Patterns + +How you connect matters as much as what you connect to. Pointing directly at your production database works fine for small internal dashboards with light query loads. As dashboards scale, heavy analytical queries during peak hours compete with transactional workloads. The better approach is connecting to a read replica, caching results where appropriate, or scheduling refreshes during off-peak windows. Reflex's background job system handles scheduled refreshes without requiring separate infrastructure. + +### Centralized Credential Management + +One practical architectural choice worth noting is project-level integration configuration. Database credentials, connection strings, and auth tokens are set once at the project level and shared automatically across every app in that project. When you fork an app, integrations carry over with no manual reconfiguration and no credential drift across a growing dashboard portfolio. + +| Database Type | Connection Method | Use Case | Reflex Support | +|---|---|---|---| +| PostgreSQL | Direct or read replica | OLTP applications, analytics | Native via SQLAlchemy | +| MongoDB | Connection string | Document storage, unstructured data | Native via pymongo | +| MySQL | Direct or read replica | Web applications, transactional data | Native via SQLAlchemy | +| Snowflake | JDBC or Python connector | Data warehouse, analytics at scale | Native integration | +| Supabase | REST API or direct Postgres | Real-time apps, collaborative tools | Native integration | + +For anything not in that list, the PyPI ecosystem covers it. Databricks, DuckDB, BigQuery, ClickHouse: if a Python connector exists, it works inside Reflex without additional setup. + +## Key Dashboard Components for Database Data + +Matching the right component to your data type is the foundation of dashboard design. Aggregate metrics belong in stat cards, row-level query results belong in tables, and trends over time belong in charts. Squeezing everything into one layout creates noise instead of clarity. The best dashboards show whether metrics are improving, declining, or holding steady. + +### Tables for Relational Data Display + +Tables handle sortable columns, pagination, row selection, and inline editing well. Learn more about [creating tables in Reflex](https://reflex.dev/blog/using-table-component/) for relational data. For financial or high-density datasets, [AG Grid in Reflex](https://reflex.dev/blog/using-ag-grid-in-reflex/) wraps cleanly via Reflex's React component system, giving you spreadsheet-level control inside a web app. + +### Charts for Time-Series Metrics + +Line charts work for query latency over time, bar charts for categorical breakdowns, and area charts for cumulative counts. Check out [new core graphing components](https://reflex.dev/blog/graphing-update/) for advanced visualizations. Reflex's charting library supports Plotly for interactive visualizations, with state-driven updates that refresh charts the moment underlying data changes. + +### Filters and Query Parameters + +Filter inputs tied to computed vars re-execute queries automatically on change. Date ranges, dropdowns, and search fields modify WHERE clauses without manual wiring. A good rule of thumb: add filters when users need three or more views of the same data, such as region, channel, and time period comparisons. + +### Real-Time Update Components + +WebSocket sync pushes server state to the browser instantly. Live counters, notification badges, and streaming log feeds update without polling, because state changes on the backend propagate to every connected client automatically. + +## Deploying Your Database Dashboard to Production + +Deploying a dashboard packages your full-stack Python app, including database connection logic, state management, and UI, into a single deployable unit. There are no separate frontend and backend pipelines to coordinate. The entire application ships together, which removes a common failure point in traditional web deployments. + +### Cloud Deployment for Scalable Dashboards + +[Reflex Cloud](https://reflex.dev/hosting/) handles infrastructure provisioning automatically, with Helm chart orchestration for Kubernetes environments and multi-region deployment for global teams. CI/CD pipelines via GitHub Actions or GitLab CI slot in without custom configuration. Concurrency scales with query load without requiring manual intervention. Built-in OpenTelemetry distributed tracing and ClickHouse log aggregation give you visibility into query latency, connection pool behavior, and user concurrency patterns from day one. + +### Enterprise Deployment with Database Access Controls + +For industries with compliance requirements, database traffic should never leave your network perimeter. [Reflex supports self-hosted on-premises deployment](https://reflex.dev/blog/on-premises-deployment/) and VPC isolation, keeping query traffic private. RBAC controls which users see which data, and audit logging tracks every access event for compliance teams. + +| Deployment Option | Best For | Database Access Pattern | Compliance Features | +|---|---|---|---| +| Reflex Cloud | Rapid deployment, cloud databases | Public internet or VPC peering | SOC 2, RBAC, audit logs | +| On-Premises | Industries with compliance requirements, air-gapped networks | Private network only | Full data sovereignty, custom security policies | +| Hybrid | Global teams with regional data requirements | Read replicas per region | Regional compliance, RBAC per deployment | + +## FAQ + +### Can I build a database dashboard without JavaScript? + +Yes. Reflex lets you build full database dashboards in pure Python, including queries, state management, and UI components, without writing any JavaScript. This works for PostgreSQL, MongoDB, MySQL, Snowflake, and any database with a Python connector. + +### Reflex vs Streamlit for database dashboards? + +Reflex supports event-based state updates and server push, while Streamlit reruns the entire script on every interaction, causing memory leaks and slowdowns under load. Reflex also provides built-in auth, background jobs, and custom CSS control that Streamlit lacks, making it better for production database dashboards. + +### How do I connect a PostgreSQL database to a Reflex dashboard? + +You connect using SQLAlchemy directly in your Reflex state class, just like a standard Python script. Database credentials are configured once at the project level and shared across all apps automatically. Queries run inside event handlers, and results update the UI instantly through Reflex's state sync. + +### What's the best deployment option for a production database dashboard? + +Reflex Cloud handles infrastructure automatically with OpenTelemetry tracing and multi-region scaling, ideal for cloud databases. For industries with compliance requirements or private networks, self-hosted on-premises deployment keeps database traffic within your security perimeter with full VPC isolation and RBAC controls. + +### When should I use a read replica instead of the production database? + +Switch to a read replica when heavy analytical queries during peak hours slow down your production application. Database dashboards with complex aggregations, reporting workloads, or high concurrent users should always point at read replicas to separate analytical load from transactional workloads. diff --git a/blog/build-dashboard-with-gemini.md b/blog/build-dashboard-with-gemini.md new file mode 100644 index 000000000..6c69d65ff --- /dev/null +++ b/blog/build-dashboard-with-gemini.md @@ -0,0 +1,142 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Gemini in 2026" +title_tag: "Build Gemini Dashboard April 2026" +description: "Learn how to build production-ready dashboards with Gemini 3.1 Pro using Python. Complete guide with streaming APIs and deployment tips for April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Gemini dashboard Python, Google Gemini dashboard, Gemini API metrics, AI dashboard Python, Gemini analytics" + } +] +faq: [ + {"question": "Can I build a Gemini dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full Gemini dashboards in pure Python, from API integration to streaming UI updates. You handle Gemini 3.1 Pro requests, state management, and real-time response rendering through Python classes your team already knows how to debug."}, + {"question": "Gemini 3.1 Pro vs Gemini 3 Flash for dashboards?", "answer": "Gemini 3.1 Pro handles deep reasoning tasks like financial modeling or multi-source aggregation where accuracy matters more than speed. Gemini 3 Flash is better for high-frequency dashboard queries where low latency and cost matter most—think real-time KPI updates or rapid iteration on layout generation."}, + {"question": "How do I stream Gemini responses to my dashboard in real time?", "answer": "Use Gemini's `streamGenerateContent` with Reflex's WebSocket-based state sync. Each response chunk from Gemini gets pushed to the UI as it's generated, without custom polling infrastructure. The pattern works the same whether you're streaming text, processing function calls, or handling multimodal inputs."}, + {"question": "What's the fastest way to deploy a Gemini dashboard to production in 2026?", "answer": "Run `reflex deploy` to package your entire Gemini dashboard into a single artifact with no separate frontend and backend pipelines. For teams that need self-hosted infrastructure due to data sovereignty requirements, Reflex provides Helm charts for Kubernetes orchestration."}, + {"question": "How does Reflex handle concurrent Gemini API requests better than Streamlit?", "answer": "Reflex uses an async server architecture that handles multiple simultaneous Gemini 3.1 Pro requests without performance degradation, while Streamlit struggles under concurrent load due to full script re-execution on every interaction. This makes Reflex more suitable for production dashboards with multiple users."}, + {"question": "Can Gemini dashboards process image inputs along with text?", "answer": "Yes. Gemini supports multimodal inputs that combine text prompts with uploaded images or documents, enabling use cases like document review, medical imaging interfaces, or satellite monitoring within your dashboard."}, + {"question": "What's the advantage of project-level API credential configuration in Reflex?", "answer": "Instead of adding Gemini API credentials to each dashboard app separately, you define them once at the project level and every app inherits them automatically. This simplifies credential management, reduces duplication, and makes API key rotation much easier across multiple dashboards."}, + {"question": "How much does it cost to run Gemini 3.1 Pro in a production dashboard?", "answer": "Gemini 3.1 Pro costs $2-$4 per 1M input tokens and $12-$18 per 1M output tokens as of early 2026. For cost-sensitive applications with high query volumes, Gemini 3 Flash offers a more economical alternative while maintaining good performance."}, + {"question": "What is Gemini's function calling capability and why does it matter for dashboards?", "answer": "Function calling lets Gemini query databases or external APIs and return structured results that your Reflex state can act on directly. This enables real-time data retrieval workflows where the dashboard can dynamically pull information based on user queries."}, + {"question": "Can I self-host a Gemini dashboard if I can't use cloud APIs?", "answer": "Yes. Reflex provides self-hosted infrastructure options with Helm charts for Kubernetes orchestration when data sovereignty requirements rule out cloud API calls. You maintain full control over where your dashboard and data reside."}, + {"question": "What's the difference between Flex Inference and Priority Inference for Gemini dashboards?", "answer": "Flex Inference uses dynamic resource allocation to reduce costs for non-urgent workloads, while Priority Inference ensures faster response times when latency matters. Choose based on whether your dashboard prioritizes cost optimization or real-time responsiveness."}, + {"question": "How does Reflex push real-time updates without polling?", "answer": "Reflex uses WebSocket-based state synchronization to push updated state to every connected client instantly when new Gemini responses arrive. This eliminates the need for custom polling infrastructure and keeps dashboards responsive during streaming operations."}, + {"question": "What components does Reflex provide for displaying Gemini-generated data?", "answer": "Reflex offers 60+ built-in components including streaming text displays, data tables (including AG Grid wrappers), Plotly and Recharts visualizations, stat cards, and chat interfaces. These cover the most common dashboard patterns for Gemini data without requiring custom UI code."}, + {"question": "How do I track and manage Gemini API costs in production?", "answer": "Reflex Cloud provides a Token Economics Dashboard that lets you track token consumption and catch cost spikes before they compound. Store API keys as environment variables and monitor usage patterns to optimize which model (Pro vs Flash) you use for different query types."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Gemini 3.1 Pro builds agentic dashboards that query databases and stream visualizations in real time + +- Reflex handles Gemini's streaming API through Python state classes without JavaScript bottlenecks + +- Deploy production-ready Gemini dashboards with `reflex deploy` and project-level API credential sharing + +- Reflex is a Python framework that lets you build full-stack web apps without learning JavaScript + +## What You Can Build: Gemini Dashboard Overview + +Building a dashboard with Gemini goes well beyond dropping a chart on a page. With Gemini 3.1 Pro, you get a frontier reasoning model capable of synthesizing complex, multi-source data into live interfaces. Google's own testing showed the model [building a live aerospace dashboard](https://deepmind.google/models/gemini/pro/) by configuring a public telemetry stream to visualize the International Space Station's orbit, generating animated SVGs and interactive components entirely through code output. + +That gives you a sense of the range. On the simpler end, teams wire Gemini to query results and surface KPIs in a clean layout. On the more capable end, you get agentic workflows: a user types a question, Gemini queries a database, generates a visualization, and streams the result back without a page refresh. + +Here are a few categories of dashboards that Gemini handles well: + +- Multimodal analysis tools that accept both text and image inputs, opening up use cases like document review, medical imaging interfaces, or satellite monitoring. + +- Real-time KPI dashboards where Gemini 3 Flash handles high-frequency data calls at low latency. + +- Complex reasoning interfaces where Gemini 3.1 Pro takes over for tasks where accuracy outweighs speed, such as [financial modeling or multi-source aggregation](https://reflex.dev/blog/top-10-data-visualization-libraries/). + +The model you reach for depends on what your dashboard needs to do. Fast, frequent queries go to Gemini 3 Flash. Deep, multi-step reasoning tasks belong to Gemini 3.1 Pro. + +## Why Python Developers Choose Reflex for Gemini Dashboards + +Python data teams building Gemini dashboards face a real decision: keep everything in Python, or introduce a JavaScript frontend that splits your logic across two languages and two skill sets. For most teams, that split creates a bottleneck where domain experts can't touch the frontend code they need to modify most. + +Reflex keeps the entire stack in Python. State management, Gemini API calls, and UI updates all live in the same Python classes your team already reads and debugs. Gemini's `streamGenerateContent` streams response chunks as they're generated, and Reflex's WebSocket-based state sync pushes those chunks to the UI in real time without custom polling infrastructure. [Gemini's Live API](https://ai.google.dev/gemini-api/docs/live-api) extends this further, allowing low-latency, continuous audio and vision streams that Reflex handles through the same event-driven model. + +Where frameworks like Streamlit struggle under concurrent load due to full script re-execution on every interaction, Reflex's async server architecture handles multiple simultaneous Gemini 3.1 Pro requests without degrading. You get 60 built-in components covering charts, tables, and inputs, plus the ability to [wrap any React library](https://reflex.dev/blog/custom-components/) when you need something more specific. + +> + +"It's like Streamlit for adults. It's fast, it looks good, and we don't need to throw it away after prototyping." - Delta Global Head of Quant + +That's the core tradeoff covered in our [Reflex vs Streamlit](https://reflex.dev/blog/reflex-streamlit/) comparison: prototype speed with production staying power. + +## Connecting Gemini to Your Reflex App + +Getting Gemini connected is straightforward because Reflex treats it like any other Python dependency. There's no separate API layer to configure, no proxy service to stand up. The `google-genai` package installs via pip and slots directly into your Reflex state classes, where event handlers call the API, process responses, and update state all in one place. + +Gemini 3.1 Pro is Google's most capable reasoning model, [priced at $2-$18 per 1M tokens](https://www.metacto.com/blogs/the-true-cost-of-google-gemini-a-guide-to-api-pricing-and-integration) as of early 2026. For high-frequency dashboard queries where cost and latency matter more than reasoning depth, Gemini 3 Flash is the practical choice. + +One feature worth knowing about is Reflex's project-level integration configuration. Instead of adding your Gemini API credentials to each dashboard app separately, you define them once at the project level and every app within that project inherits them. That matters when you're managing multiple dashboards against Google AI Studio or Vertex AI, since it cuts down on credential duplication and simplifies rotation. + +From there, the patterns you'd reach for most often are: + +- Streaming responses using `streamGenerateContent`, where Reflex's WebSocket sync pushes each chunk to the UI as Gemini generates it, keeping the dashboard feeling responsive even during longer queries. + +- Function calling for real-time data retrieval, letting Gemini query a database or external API and return structured results your state can act on directly. + +- Multimodal inputs that combine text prompts with uploaded images or documents, opening up richer analysis workflows beyond what text-only queries can handle. + +## Key Dashboard Components for Gemini Data + +Most Gemini dashboards surface four recurring patterns: streaming text, structured data tables, charts, and stat cards. Reflex's component library maps directly to each one, so you're composing known primitives instead of wiring custom UI from scratch. + +Gemini 3 Flash is particularly well-suited here. Its tool calling and structured output support lets it [assemble dashboards via rapid iteration](https://www.datacamp.com/tutorial/building-with-gemini-3-1-pro-coding-agent-tutorial), functioning almost like a UI studio that generates layout specs your Reflex state can act on immediately. + +| Component Type | Reflex Implementation | Gemini Use Case | +|---|---|---| +| Streaming Text | rx.text with yield updates | Display token-by-token LLM responses | +| Data Tables | rx.data_table, AG Grid wrapper | Show structured function call results | +| Charts | Plotly/Recharts components | Visualize Gemini-generated analytics | +| Stat Cards | rx.stat, rx.card | Surface extracted metrics from queries | +| Chat Interface | rx.text_area with message history | Conversational dashboard queries | + +The glue holding these together is Reflex's state layer. Computed vars process raw Gemini API responses into calculated metrics, filtered lists, or aggregated totals before they ever reach the UI. When a new Gemini response arrives, WebSocket synchronization pushes updated state to every connected client instantly, no polling required. + +## Deploying Your Gemini Dashboard to Production + +Once your dashboard is ready, getting it live is straightforward. Run ``[reflex deploy](https://reflex.dev/hosting/) and Reflex packages your entire Gemini dashboard, streaming infrastructure included, into a single artifact with no separate frontend and backend pipelines to manage. You can follow the deploy quick start or go with [self-hosted infrastructure](https://reflex.dev/blog/self-hosting-reflex-with-docker/) when data sovereignty rules out cloud API calls, with Helm charts handling Kubernetes orchestration either way. + +A few production considerations worth locking in early: + +- Store Gemini API keys as environment variables, not in code, to avoid accidental exposure in version control. + +- Use [Flex Inference for non-urgent workloads](https://www.aibucket.io/post/gemini-api-updates-boost-google-ai-efficiency) to cut costs through flexible resource allocation, and switch to Priority Inference when response latency matters. + +- Wire GitHub Actions or GitLab CI to trigger deploys on commit so releases stay repeatable and auditable. + +- Track token consumption through Reflex Cloud's Token Economics Dashboard to catch cost spikes before they compound. + +Vertex AI credentials, database connections, and [auth providers](https://reflex.dev/blog/implementing-sign-in-with-google/) are all configurable once at the project level, so every dashboard you ship inherits them automatically. + +## FAQ + +### Can I build a Gemini dashboard without JavaScript? + +Yes. Reflex lets you build full Gemini dashboards in pure Python, from API integration to streaming UI updates. You handle Gemini 3.1 Pro requests, state management, and real-time response display through Python classes your team already knows how to debug. + +### Gemini 3.1 Pro vs Gemini 3 Flash for dashboards? + +Gemini 3.1 Pro handles deep reasoning tasks like financial modeling or multi-source aggregation where accuracy matters more than speed. Gemini 3 Flash is better for high-frequency dashboard queries where low latency and cost matter most-think real-time KPI updates or rapid iteration on layout generation. + +### How do I stream Gemini responses to my dashboard in real time? + +Use Gemini's `streamGenerateContent` with Reflex's WebSocket-based state sync. Each response chunk from Gemini gets pushed to the UI as it's generated, without custom polling infrastructure. The pattern works the same whether you're streaming text, processing function calls, or handling multimodal inputs. + +### What's the fastest way to deploy a Gemini dashboard to production in 2026? + +Run `reflex deploy` to package your entire Gemini dashboard into a single artifact with no separate frontend and backend pipelines. For teams that need self-hosted infrastructure due to data sovereignty requirements, Reflex provides Helm charts for Kubernetes orchestration. diff --git a/blog/build-dashboard-with-groq.md b/blog/build-dashboard-with-groq.md new file mode 100644 index 000000000..97c819676 --- /dev/null +++ b/blog/build-dashboard-with-groq.md @@ -0,0 +1,139 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Groq in 2026" +title_tag: "Build Groq Dashboard 2026 - Python Guide" +description: "Learn how to build a dashboard with Groq in April 2026. Step-by-step guide to creating real-time analytics dashboards using Groq and Reflex with Python." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Groq dashboard Python, Groq API dashboard, fast LLM dashboard, Groq inference metrics, Groq Python app, AI speed dashboard" + } +] +faq: [ + {"question": "Can I build a Groq dashboard without JavaScript?", "answer": "Yes. Reflex allows you to build full Groq dashboards in pure Python, with streaming responses and real-time UI updates handled through native WebSocket sync. The entire stack runs without writing any JavaScript code."}, + {"question": "Groq dashboard Reflex vs Streamlit?", "answer": "Reflex handles streaming responses through WebSocket-based state sync that pushes updates as tokens arrive, while Streamlit cannot push server-side updates to the browser at all. For Groq's 750–900 tokens per second, Reflex delivers real-time streaming experiences that Streamlit's rerun model cannot match."}, + {"question": "How do I handle Groq streaming responses in Reflex?", "answer": "Store your Groq API key in an environment variable and initialize the client inside your Reflex state class. Use `yield` statements inside event handlers to push incremental UI updates as Groq sends tokens, and the WebSocket connection delivers them to the browser automatically."}, + {"question": "What are the rate limits for Groq dashboards in production?", "answer": "Groq's Developer plan provides up to 500,000 requests per day for llama-3.1-8b-instant, compared to 14,400 on the free tier. Rate limits apply per organization rather than per API key, so isolated usage pools for separate teams require separate Groq organizations."}, + {"question": "What models does Groq support for building dashboards?", "answer": "Groq supports Llama 3.3 70B at 750-900 tokens per second and llama-3.1-8b-instant, both accessible through OpenAI-compatible API endpoints. The blog specifically benchmarks performance with Llama 3.3 70B for real-time conversational analytics dashboards."}, + {"question": "Why is Groq faster than other inference providers?", "answer": "Groq delivers 750-900 tokens per second on Llama 3.3 70B, roughly 20 times faster than competing inference providers, using specialized LPU infrastructure. This speed enables responses to arrive before users finish reading the previous one in conversational interfaces."}, + {"question": "Can Groq write data back to databases in my dashboard?", "answer": "No, Groq is a read-only inference API. Your dashboard focuses on retrieving model outputs for display, analysis, and conversation rather than complex bidirectional workflows where the LLM writes data back."}, + {"question": "What visualization libraries can I use with Reflex for Groq dashboards?", "answer": "Reflex ships with 60+ built-in components out of the box and allows you to wrap any React visualization library when you need specialized charts or graphs. This flexibility matters because Groq's high throughput shifts the bottleneck from the API to your rendering layer."}, + {"question": "How does Reflex handle WebSocket connections for streaming?", "answer": "Reflex uses native WebSocket-based state sync to push each token directly to the browser the moment it arrives from Groq. There's no polling, no separate WebSocket server to configure, and updates happen automatically through the framework's event-driven architecture."}, + {"question": "What types of dashboards work best with Groq's speed?", "answer": "The most compelling dashboards fall into three categories: real-time conversational analytics interfaces, streaming data visualization tools with LLM-generated commentary, and interactive monitoring panels with AI-generated alerts. All benefit from Groq's sub-second response times."}, + {"question": "How much code reduction does Reflex provide compared to other frameworks?", "answer": "Real Reflex projects run at roughly 50% less code than equivalent frameworks. This reduced surface area makes debugging easier when model outputs behave unexpectedly, since you can trace exactly what state triggered issues through plain Python."}, + {"question": "Does Reflex require a separate frontend build pipeline for deployment?", "answer": "No, running `reflex deploy` packages your entire dashboard as a single artifact with Python backend logic, streaming handlers, and state sync included. There's no separate frontend build pipeline and no API gateway to configure."}, + {"question": "How do I track Groq API performance metrics in my dashboard?", "answer": "Track elapsed time between request initiation and streaming completion inside your event handler, then expose it as a computed var. Stat card components can update alongside the stream to show live tokens-per-second displays without extra infrastructure."}, + {"question": "Where should I store Groq API credentials in a Reflex project?", "answer": "Store your Groq API key in an environment variable and initialize the client inside your Reflex state class constructor. Reflex Cloud's environment configuration or Kubernetes secrets for self-hosted deployments inject credentials without touching version control or compiled bundles."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Groq delivers 750-900 tokens per second on Llama 3.3 70B, which powers real-time conversational analytics dashboards where users query datasets in natural language without perceptible lag. + +- Reflex handles Groq's streaming responses natively through WebSocket-based state sync, pushing each token to the browser instantly without polling or separate infrastructure. + +- Groq provides OpenAI-compatible endpoints that work directly with Python client libraries inside Reflex state classes, with no middleware or API translation required. + +- Reflex is an open-source Python framework that builds full-stack web apps without JavaScript, used by 40% of Fortune 500 companies and powering over 1 million applications. + +## What You Can Build: Groq Dashboard Overview + +Groq's inference speed changes what a dashboard can realistically do. At [750-900 tokens per second](https://groq.com/the-official-groq-speed-benchmark/) on Llama 3.3 70B, roughly 20 times faster than competing inference providers, responses arrive before users finish reading the previous one. That speed directly shapes what you can build. + +With Reflex and Groq together, the most compelling dashboards fall into three categories: + +- Real-time conversational analytics interfaces where users query datasets in plain language and get structured, readable responses instantly + +- Streaming data visualization tools that layer LLM-generated commentary on top of live charts, trend lines, or model outputs (see our [Reflex templates](https://reflex.dev/templates/) for examples) + +- Interactive monitoring panels that surface AI-generated alerts or summaries as conditions change, without any perceptible lag + +One thing worth calling out upfront: Groq is a read-only inference API. Your dashboard won't be writing data back to Groq. What it does is retrieve model outputs fast, so your app focuses on display, analysis, and conversation instead of complex bidirectional workflows. + +Reflex handles this well. Its component library covers everything from streaming text displays to charts, and its WebSocket-based state sync means the UI updates the moment new tokens arrive. You're building for speed, and the framework keeps up. + +## Why Python Developers Choose Reflex for Groq Dashboards + +Python teams building Groq dashboards face a familiar fork in the road: write a React frontend to handle streaming responses properly, or accept the [limitations of tools like Streamlit](https://reflex.dev/blog/reflex-streamlit/) that cannot push server-side updates to the browser at all. Reflex removes that choice entirely. + +The entire dashboard lives in one Python file. Groq API calls, state management, and real-time UI updates all run through Reflex's event-driven architecture without any JavaScript layer. When a Groq response starts streaming, Reflex's native WebSocket sync pushes each token directly to the browser the moment it arrives. No polling. No separate WebSocket server to configure and maintain. + +On the component side, Reflex ships 60+ built-in components out of the box, and you can wrap any React visualization library when you need something more specialized. Groq's throughput is high enough that your bottleneck moves from the API to your display layer, so having that flexibility matters. Real Reflex projects also run at roughly 50% less code than equivalent frameworks, which means less surface area to debug when model outputs behave unexpectedly. + +Low-code tools fall short here for a specific reason: they cannot maintain readable Python code against a streaming API. When your LLM output looks wrong, you need to trace exactly what state triggered it. With Reflex, that trace is plain Python all the way down. + +## Connecting Groq to Your Reflex App + +Groq provides [OpenAI-compatible API endpoints](https://console.groq.com/docs/overview) that work directly with standard Python client libraries. There's no middleware layer, no proxy configuration, and no API translation required. Because [Reflex runs a FastAPI backend](https://reflex.dev/blog/reflex-architecture/) and supports any PyPI package, you install the Groq SDK the same way you'd install any Python dependency and call it from within your app's state class. + +Reflex's project-level integration configuration makes credential management clean across teams. Instead of hardcoding API keys per app, you configure Groq credentials once at the project level and every dashboard in that project inherits access automatically. That matters when you're building separate analytics interfaces for different model endpoints and don't want to chase down per-app key drift. + +### API Configuration in Reflex State Classes + +Store your Groq API key in an environment variable and initialize the client inside your [Reflex state class](https://reflex.dev/overview/) constructor. This keeps authentication logic in one place while making inference methods available to any event handler across the entire app. Any page component can trigger a Groq call through shared state without duplicating credential setup. + +### Handling Streaming Responses + +Reflex's `yield` statement pattern inside event handlers is what makes streaming feel native. As Groq sends tokens, each `yield` pushes an incremental UI update over WebSocket without any custom client-side code. Compared to frameworks that require polling or manual JavaScript handling, this keeps the stack entirely in Python while delivering the [streaming experience](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) users expect. + +## Key Dashboard Components for Groq Data + +Groq returns text and JSON, not time-series arrays or tabular datasets. That shapes every component decision. The most effective Groq dashboards focus on conversational interfaces and structured response visualization. + +### Chat Interface Patterns + +Message history is stored as a Python list in your state class, where each completed Groq response appends a new entry. Display uses `rx.foreach` to iterate over that list, applying consistent message styling per turn. Scroll-to-bottom behavior triggers as an event handler side effect after each append, so users never manually scroll mid-conversation. `rx.text` handles the streaming output itself, updating character-by-character as each `yield` pushes new tokens through WebSocket. + +### Real-Time Inference Metrics + +Because Groq's LPU throughput is genuinely fast, showing that speed in the UI reinforces the product value. Track elapsed time between request initiation and streaming completion inside your event handler, then expose it as a computed var. [Stat card components](https://reflex.dev/blog/custom-components/) update alongside the stream, giving users a live tokens-per-second display without any extra infrastructure. + +| Component Type | Reflex Implementation | Groq Use Case | Update Pattern | +|---|---|---|---| +| Chat message list | `rx.foreach` with conversation state | Display conversation history | Append on completion | +| Streaming text | `rx.text` with state var | Show real-time LLM output | Update on yield | +| Metrics dashboard | `rx.stat` components | Inference speed tracking | Calculate on complete | +| Model comparison | `rx.table` with columns | Side-by-side outputs | Parallel API calls | + +## Deploying Your Groq Dashboard to Production + +Once your dashboard is ready, getting it to production is straightforward. Running ``[reflex deploy](https://reflex.dev/hosting/) packages your entire Groq dashboard as a single artifact, with Python backend logic, streaming handlers, and state sync included. There is no separate frontend build pipeline and no API gateway to configure. Reflex Cloud's multi-region deployment keeps latency low for distributed teams, while Groq's centralized LPU infrastructure maintains consistent inference speed regardless of where users connect from. For internal analytics tools querying proprietary data through Groq-powered interfaces, VPC and on-premises options keep credentials and conversation logs inside your security boundary. + +### Environment and Secrets Management + +Groq API keys get injected through Reflex Cloud's environment configuration or Kubernetes secrets for self-hosted deployments, so credentials never touch version control or compiled bundles. + +### Monitoring Groq API Usage + +[Instrument your event handlers](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) to track request counts, token consumption, and error rates. These feed into Reflex Cloud's OpenTelemetry integration or custom logging handlers for self-hosted setups. One thing worth planning around: Groq's Developer plan raises limits considerably, with llama-3.1-8b-instant jumping from [14,400 to 500,000 requests per day](https://console.groq.com/docs/rate-limits). Rate limits also apply per organization instead of per API key, so if you need isolated usage pools for separate teams, that requires separate Groq organizations. + +## FAQ + +### Can I build a Groq dashboard without JavaScript? + +Yes. Reflex allows you to build full Groq dashboards in pure Python, with streaming responses and real-time UI updates handled through native WebSocket sync. The entire stack runs without writing any JavaScript code. + +### What's the main difference between Reflex and Streamlit for Groq dashboards? + +Reflex handles streaming responses through WebSocket-based state sync that pushes updates as tokens arrive, while Streamlit cannot push server-side updates to the browser at all. For Groq's 750-900 tokens per second, Reflex delivers real-time streaming experiences that Streamlit's rerun model cannot match. + +### How do I handle Groq streaming responses in Reflex? + +Store your Groq API key in an environment variable and initialize the client inside your Reflex state class. Use `yield` statements inside event handlers to push incremental UI updates as Groq sends tokens, and the WebSocket connection delivers them to the browser automatically. + +### What are the rate limits for Groq dashboards in production? + +Groq's Developer plan provides up to 500,000 requests per day for llama-3.1-8b-instant, compared to 14,400 on the free tier. Rate limits apply per organization instead of per API key, so isolated usage pools for separate teams require separate Groq organizations. + +### How do I deploy my Groq dashboard to production? + +Run `reflex deploy` to package your entire dashboard as a single artifact with Python backend logic, streaming handlers, and state sync included. There's no separate frontend build pipeline or API gateway to configure, and Groq API keys get injected through environment configuration. diff --git a/blog/build-dashboard-with-postgresql.md b/blog/build-dashboard-with-postgresql.md new file mode 100644 index 000000000..78dd331c1 --- /dev/null +++ b/blog/build-dashboard-with-postgresql.md @@ -0,0 +1,143 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With PostgreSQL in 2026" +title_tag: "Build a PostgreSQL Dashboard in 2026" +description: "Learn how to build a PostgreSQL dashboard in Python with Reflex. Complete tutorial for creating production-ready database dashboards in April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "PostgreSQL dashboard Python, Postgres dashboard, SQL dashboard Python, database analytics, PostgreSQL metrics Python" + } +] +faq: [ + {"question": "Can I build a PostgreSQL dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full PostgreSQL dashboards in pure Python, including queries, connection pooling, real-time updates, and UI components. Your database driver, event handlers, and visualization components all stay in Python without needing a separate JavaScript frontend."}, + {"question": "Reflex vs Streamlit for PostgreSQL dashboards?", "answer": "Streamlit re-executes your entire script on every interaction, which creates memory leaks and makes dynamic filtering unreliable at scale. Reflex uses an event-based model where specific user interactions trigger targeted database queries, keeping connections and state clean across concurrent users."}, + {"question": "How do I handle connection pooling for concurrent dashboard users?", "answer": "Use psycopg3's `AsyncConnectionPool` initialized once at application startup through a FastAPI lifespan context. This keeps a capped set of warm connections ready, reducing latency from repeated handshakes when multiple analysts query your PostgreSQL database simultaneously."}, + {"question": "What's the fastest way to deploy a production PostgreSQL dashboard in 2026?", "answer": "Run `reflex deploy` to package your entire application—including PostgreSQL connection logic, queries, and dashboard UI—into a production deployment. Reflex provisions the FastAPI backend and React frontend together, keeping state synchronization intact for concurrent users without manual infrastructure setup."}, + {"question": "When should I use VPC deployment for my PostgreSQL dashboard?", "answer": "If your PostgreSQL instance sits behind a firewall in a private network due to compliance requirements (common in finance, healthcare, or government), VPC deployment lets your Reflex dashboard run inside your controlled environment with direct network access to those databases."}, + {"question": "What types of PostgreSQL dashboards can I build with Reflex?", "answer": "Reflex supports both read-only analytics dashboards for reporting and business intelligence, as well as read-write CRUD dashboards that let non-technical stakeholders manage transactional data directly through a UI. Both types use the same consistent architecture with Reflex's component library and database integration layer."}, + {"question": "Does Reflex work with SQLAlchemy for PostgreSQL connections?", "answer": "Yes. Reflex compiles to a FastAPI backend with Uvicorn, so it works with standard Python database drivers including both psycopg3 and SQLAlchemy. You write the same connection code you would in any Python service and wire it into Reflex's event handlers."}, + {"question": "How do I visualize time-series data from PostgreSQL in Reflex?", "answer": "Time-series data from PostgreSQL maps cleanly to Plotly or Recharts integrations in Reflex. Use line charts for trends, bar charts for categorical aggregations, and store query results in computed vars that update reactively when users interact with filters or controls."}, + {"question": "Can I use AG Grid with PostgreSQL data in Reflex?", "answer": "Yes. You can wrap AG Grid or similar React data grids in pure Python to get features like sortable columns, pagination, and inline filtering. Computed vars hold your PostgreSQL query results reactively, so tables update without page reloads when users sort or filter."}, + {"question": "How does Reflex handle real-time dashboard updates from PostgreSQL?", "answer": "Reflex uses WebSocket sync to update dashboard components in real-time without full page reloads. Stat cards and charts refresh automatically through event handlers that trigger new PostgreSQL queries, keeping metrics current for concurrent users."}, + {"question": "What environment variables do I need to connect PostgreSQL to Reflex?", "answer": "Your PostgreSQL connection string lives in an environment variable, following standard Python patterns. For teams managing multiple dashboards, Reflex Cloud lets you define PostgreSQL credentials once at the project level so every application inherits the connection automatically."}, + {"question": "How do I monitor PostgreSQL query performance in my Reflex dashboard?", "answer": "Reflex Cloud's OpenTelemetry integration and ClickHouse log aggregation surface query latency and error rates across dashboard sessions. At the database level, configure logging for pgBadger analysis and set alerts for connection exhaustion and slow queries to optimize indexes."}, + {"question": "Can I build CRUD interfaces for PostgreSQL with Reflex?", "answer": "Yes. Reflex supports read-write dashboards that give non-technical stakeholders a way to interact with live PostgreSQL records safely. Built-in RBAC controls which users can execute write operations against specific tables, so analysts get what they need without unauthorized access."}, + {"question": "What database metrics should I display on a PostgreSQL monitoring dashboard?", "answer": "Key metrics include cache hit ratio (alert below 99%), replication lag (alert above 5 seconds), disk usage (alert above 80%), connection count, and query performance. Reflex stat cards can surface these metrics with real-time refresh via WebSocket sync."}, + {"question": "How does Reflex handle database connections during application shutdown?", "answer": "Reflex uses a FastAPI lifespan context to initialize the AsyncConnectionPool at startup and close it cleanly at shutdown. This ensures connections are properly released without leaving orphaned database connections when the server stops."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build PostgreSQL dashboards entirely in Python with Reflex, skipping JavaScript entirely. + +- Psycopg3's AsyncConnectionPool handles concurrent users without connection exhaustion. + +- Reflex Cloud VPC deployment keeps your database behind firewalls for industries with compliance requirements. + +- Reflex is a full-stack Python framework that outputs readable, maintainable code for production apps. + +## What You Can Build: PostgreSQL Dashboard Overview + +PostgreSQL sits at the center of more production systems than most developers realize. Your application database, your analytics warehouse, your transactional records: chances are PostgreSQL already holds the data your team needs to act on. [Most teams reach for database dashboard tools](https://www.basedash.com/blog/best-database-dashboard-tools-in-2026) to [visualize their database data](https://reflex.dev/templates/database-visualization/), and that instinct is right. You point it at the database your application already uses and start building dashboards on top of live data. + +The scope of what you can build on top of that data goes well beyond a simple chart viewer. Analysts pull production metrics from application tables and surface them as live KPI monitors. Executives get business forecasting views built from aggregated historical records. Operations teams watch resource usage tick up in real time. Data engineers wire up read-write interfaces so stakeholders can update records without touching SQL. + +There are two broad dashboard types worth distinguishing here: + +- Read-only analytics dashboards for reporting, trend analysis, and business intelligence, where the goal is surfacing patterns and communicating state across the organization. + +- Read-write CRUD dashboards for managing transactional data directly through a UI, giving non-technical stakeholders a way to interact with live records safely. + +Reflex handles both through a full component library and database integration layer, so your architecture stays consistent regardless of which type you are building. + +## Why Python Developers Choose Reflex for PostgreSQL Dashboards + +The traditional PostgreSQL dashboard workflow for Python developers follows a frustrating pattern: write queries in Python, then rebuild the entire data layer in JavaScript to make it interactive. That context switch costs time and introduces a second language into what should be a single-concern codebase. + +Reflex removes that layer entirely. Your PostgreSQL queries, connection state, real-time update logic, and UI components all live in Python. State classes query the database, event handlers respond to user interactions, and 60+ built-in components render the results. No JavaScript, no separate frontend repo, no API layer gluing two codebases together. + +The PyPI ecosystem plugs straight in as well, giving you access to powerful Python visualization libraries for charts and graphs. ````[Psycopg3 ships native AsyncConnection and AsyncCursor](https://medium.com/@bhagyarana80/7-psycopg3-features-that-make-postgres-fly-ef7f231babb9) so your queries work naturally with async event loops. A shared `AsyncConnectionPool` keeps connections warm and capped, which matters when your dashboard serves concurrent users. These are production-grade database patterns that integrate directly into Reflex's state model without any additional middleware. + +The contrast with alternatives is sharp. Streamlit's linear rerun model re-executes your entire script on every interaction, which creates memory leaks and makes interactive filtering unreliable at scale. Dash requires callback wiring that turns complex dashboards into maintenance headaches. React gives you flexibility but pulls data engineers away from Python entirely. Reflex gives you the event-based interactivity of a proper frontend framework without ever leaving Python. + +## Connecting PostgreSQL to Your Reflex App + +[Reflex compiles to a FastAPI backend](https://reflex.dev/blog/reflex-architecture/) with a Uvicorn async server underneath, which means PostgreSQL integration follows patterns any Python developer already knows. Connection strings, environment variables, psycopg3 or SQLAlchemy: none of that changes. You write the same connection code you would in any Python service and wire it into Reflex's event handlers, which respond to user interactions and trigger database queries against live data. + +### Database Connection Setup + +Standard database drivers plug directly into Reflex's state model. Your connection string lives in an environment variable, your query logic sits inside a state class method, and your UI components read from computed vars that reflect the latest query results. For teams managing multiple dashboards, [Reflex Cloud](https://reflex.dev/hosting/)'s project-level integration configuration lets you define PostgreSQL credentials once at the project level, and every application within that project inherits the connection automatically, so you stop repeating credential setup per app. + +### Connection Pooling for Production Scale + +Single connections break under concurrent load. [Connection pools manage and lend connections](https://access.crunchydata.com/documentation/psycopg3/3.1.9/advanced/pool.html), because opening a new connection carries real latency cost, keeping connections warm reduces response times across concurrent dashboard sessions. + +Psycopg3's `AsyncConnectionPool` fits naturally into Reflex's async event handler model. You initialize the pool once using a FastAPI lifespan context at application startup, which keeps a capped set of connections ready without opening new ones per request. When the server shuts down, the lifespan context closes the pool cleanly. For a dashboard serving multiple analysts simultaneously, this architecture means each deployment handles concurrent queries without connection exhaustion or added latency from repeated handshakes. + +## Key Dashboard Components for PostgreSQL Data + +A well-structured PostgreSQL dashboard typically needs four distinct component types, each serving a different data presentation goal. + +### Tables and Data Grids + +PostgreSQL query results slot naturally into table components for straightforward row-column display. For more demanding use cases like sortable columns, pagination, and inline filtering, you can [wrap AG Grid](https://reflex.dev/blog/using-ag-grid-in-reflex/) or similar React data grids in pure Python. Computed vars hold query results reactively, so when a user sorts a column or changes a filter, the event handler fires a new query and the table updates without a page reload. + +### Charts and Visualization + +Time-series data from PostgreSQL maps cleanly to [Plotly or Recharts](https://reflex.dev/blog/graphing-update/) integrations. Chart type follows data shape: line charts for trends, bar charts for categorical aggregations, scatter plots for correlations. + +### Real-Time Stat Cards + +[The Prometheus + Grafana stack is standard](https://tech-insider.org/postgresql-tutorial-complete-database-guide-2026/), with key alerts on cache hit ratio below 99%, replication lag above 5 seconds, and disk usage above 80%. Stat cards surface those same metrics and refresh via WebSocket sync without full page reloads. + +| Component Type | PostgreSQL Data Type | Common Use Case | +|---|---|---| +| Table | Transactional records | Customer orders, user accounts | +| Line chart | Time-series metrics | Query performance, resource usage | +| Bar chart | Aggregated counts | Sales by region, events by category | +| Stat card | Single metric | Total users, cache hit ratio | +| Filter input | Query parameter | Date range, status filter | + +## Deploying Your PostgreSQL Dashboard to Production + +Getting a Reflex dashboard into production takes a single command: `reflex deploy`. That command packages your entire application, including PostgreSQL connection logic, query functions, connection pool configuration, and dashboard UI, into a production-ready deployment. Because your database driver is a standard PyPI dependency, it ships alongside your application code without extra build steps. Reflex provisions both the FastAPI backend executing your queries and the React frontend displaying results, keeping state synchronization intact for concurrent users. + +### Database Security and VPC Deployment + +For teams in finance, healthcare, or government, compliance requirements often mean PostgreSQL sits behind a firewall in a [private network](https://reflex.dev/blog/on-premises-deployment/). Reflex Cloud's VPC deployment support lets your dashboard application run inside a customer-controlled environment with direct network access to those instances. [On-premises deployment](https://reflex.dev/blog/self-hosting-reflex-with-docker/) via Helm charts supports air-gapped environments where data never leaves your infrastructure. Built-in RBAC controls which users access specific dashboard views or execute write operations against PostgreSQL tables, so analysts get what they need without touching tables they shouldn't. + +### Monitoring and Observability + +Production PostgreSQL dashboards need two layers of observability. At the database level, [configure database logging and performance alerts](https://dev.to/_d7eb1c1703182e3ce1782/postgresql-performance-tuning-checklist-2026-complete-guide-65a) while tracking table and index bloat over time. At the application level, [Reflex Cloud's OpenTelemetry integration](https://reflex.dev/blog/reflex-v0-4-0/) and ClickHouse log aggregation surface query latency and error rates across dashboard sessions, so you can find slow queries and optimize indexes without manually instrumenting your application code. + +## FAQ + +### Can I build a PostgreSQL dashboard without JavaScript? + +Yes. Reflex lets you build full PostgreSQL dashboards in pure Python, including queries, connection pooling, real-time updates, and UI components. Your database driver, event handlers, and visualization components all stay in Python without needing a separate JavaScript frontend. + +### Reflex vs Streamlit for PostgreSQL dashboards? + +Streamlit re-executes your entire script on every interaction, which creates memory leaks and makes interactive filtering unreliable at scale. Reflex uses an event-based model where specific user interactions trigger targeted database queries, keeping connections and state clean across concurrent users. + +### How do I handle connection pooling for concurrent dashboard users? + +Use psycopg3's `AsyncConnectionPool` initialized once at application startup through a FastAPI lifespan context. This keeps a capped set of warm connections ready, reducing latency from repeated handshakes when multiple analysts query your PostgreSQL database simultaneously. + +### What's the fastest way to deploy a production PostgreSQL dashboard in 2026? + +Run `reflex deploy` to package your entire application (including PostgreSQL connection logic, queries, and dashboard UI) into a production deployment. Reflex provisions the FastAPI backend and React frontend together, keeping state synchronization intact for concurrent users without manual infrastructure setup. + +### When should I use VPC deployment for my PostgreSQL dashboard? + +If your PostgreSQL instance sits behind a firewall in a private network due to compliance requirements (common in finance, healthcare, or government), VPC deployment lets your Reflex dashboard run inside your controlled environment with direct network access to those databases. diff --git a/blog/build-dashboard-with-slack.md b/blog/build-dashboard-with-slack.md new file mode 100644 index 000000000..90a06199f --- /dev/null +++ b/blog/build-dashboard-with-slack.md @@ -0,0 +1,162 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Slack in 2026" +title_tag: "Build a Slack Dashboard in April 2026" +description: "Learn how to build a Slack dashboard in Python with Reflex in April 2026. Track messages, response times, and team activity with real-time updates." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Slack dashboard Python, Slack API dashboard, team analytics dashboard, Slack metrics Python, messaging dashboard" + } +] +faq: [ + {"question": "Can I build a Slack dashboard without JavaScript?", "answer": "Yes. Reflex handles both frontend and backend in pure Python, so you build the entire Slack integration—event handlers, message posting, and UI components—without writing any JavaScript. The framework manages WebSocket connections and state sync automatically."}, + {"question": "What's the fastest way to connect Slack's API to a Python dashboard?", "answer": "Install the `slack_sdk` package from PyPI, configure your bot token and signing secret at the project level in Reflex, then call Slack's Web API directly inside your event handlers. Reflex's WebSocket-based state sync pushes updates to the browser automatically when Slack events arrive."}, + {"question": "How do I handle Slack's 3-second webhook response requirement?", "answer": "Reflex's API routes acknowledge Slack webhooks fast enough to meet the 3-second window, while background tasks process heavy logic asynchronously. This pattern keeps your webhook handler responsive even when you're fetching paginated channel history or updating multiple components."}, + {"question": "Reflex vs Streamlit for building a Slack dashboard?", "answer": "Streamlit's script rerun model breaks under real-time Slack events—every incoming message triggers a full script re-execution, causing memory leaks and slowdowns. Reflex uses event-based state updates, so Slack events update only the affected components without re-running your entire app."}, + {"question": "What Slack data works best in a real-time dashboard?", "answer": "Message volume per channel, active user counts, response time trends, and keyword alerts all map cleanly to Reflex components. The Events API pushes workspace activity to your app in real-time, and computed vars automatically recalculate metrics like daily active members when new events arrive."}, + {"question": "How does Reflex handle real-time updates when Slack events arrive?", "answer": "Reflex uses WebSocket-based state sync to automatically push updates to the browser when Slack events arrive. When an event handler updates state, the UI reflects changes immediately without polling or client-side fetch loops, so components like message feeds and stat cards react to the same state object simultaneously."}, + {"question": "What OAuth scopes do I need for a Slack dashboard?", "answer": "The specific OAuth scopes depend on your use case, but you'll typically need permissions for reading channel history and posting messages. You configure these bot token scopes (xoxb-...) once at the project level in Reflex, and all dashboards in that project inherit them automatically."}, + {"question": "Can I run a Slack dashboard on-premises for compliance reasons?", "answer": "Yes. Reflex supports self-hosted deployments that run inside your own network boundary, so Slack webhook handlers and data processing never leave your infrastructure. This provides network-level isolation for enterprise teams handling sensitive internal data."}, + {"question": "How do I verify that incoming Slack webhooks are legitimate?", "answer": "Use the signing secret from your Slack app configuration to verify HMAC signatures on incoming requests. This ensures that webhook payloads actually originate from Slack rather than an outside source attempting to spoof event data."}, + {"question": "What happens if my Slack API call takes too long to process?", "answer": "Reflex's background tasks handle long-running Slack API calls asynchronously without blocking the UI. This means heavy operations like paginated channel history fetches run in the background while your dashboard remains responsive and doesn't freeze."}, + {"question": "How do I track message volume trends across multiple Slack channels?", "answer": "Use Reflex's data table or chart components to display message counts per channel, with computed vars automatically recalculating totals when new Slack events arrive. The Events API pushes real-time workspace activity to your app, so trends update as messages are sent."}, + {"question": "Can I trigger automated responses based on Slack events?", "answer": "Yes. Your event handlers can call Slack's Web API client to post messages back into channels when specific events occur, such as keyword alerts or workflow triggers. Because Reflex handles both directions in one Python codebase, you can react to incoming events and send outbound messages from the same handler."}, + {"question": "What Python version does the Slack SDK require?", "answer": "The Slack Python SDK requires Python 3.7 and above. Since Reflex runs on Python 3.10+, the two fit naturally together with no version conflicts, and you can call the SDK directly inside Reflex event handlers."}, + {"question": "How do I manage different Slack credentials across development and production?", "answer": "Use Reflex's config system alongside environment variables in your CI pipeline. Store bot tokens and signing secrets as environment variables, and each deployment automatically pulls the correct credentials per environment without hardcoding sensitive data."}, + {"question": "What's the advantage of project-level Slack integration in Reflex?", "answer": "Project-level integration lets you configure Slack credentials once and share them across multiple dashboards automatically. If you're running several Slack dashboards for different teams or workspaces, you avoid repeated OAuth flows and credential configuration for each individual app."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build Slack dashboards in pure Python with Reflex, tracking message volume, response times, and team activity without splitting your codebase across frontend and backend. + +- Reflex's WebSocket-based state sync updates your dashboard in real-time as Slack events arrive, with no polling or client-side fetch loops required. + +- Project-level integration configuration lets you set Slack credentials once and share them across multiple dashboards automatically. + +- Deployment takes one command and includes HTTPS endpoints that meet Slack's 3-second response requirement out of the box. + +- Reflex is a full-stack Python framework that outputs readable, maintainable code and supports on-premises deployment for enterprise compliance. + +## What You Can Build: Slack Dashboard Overview + +Slack generates a surprising amount of useful data. Every message, reaction, channel join, file upload, and thread reply is a signal. Pull those signals into a dashboard and you suddenly have visibility into how your team actually works, beyond what you assume. + +With Reflex and Slack's APIs, here's what a useful dashboard looks like in practice: + +- Workspace activity monitoring: track messages per day, active users, and peak usage hours to understand team rhythms over time. + +- Channel analytics: measure response times, thread engagement rates, and message volume trends to see where conversations actually happen. + +- Team collaboration metrics: surface cross-channel participation, reaction patterns, and user activity heatmaps to spot collaboration gaps. + +- Notification workflows: route alerts when specific keywords appear or trigger automated responses to workspace events. + +What makes Slack well-suited for this is its dual API model. The Events API pushes real-time workspace events to your app via HTTP callbacks, so your dashboard reacts to what's happening now. Incoming webhooks handle the other direction, letting your app post messages, alerts, or summaries back into Slack channels. + +> + +"The Events API delivers real-time workspace events to endpoints via HTTP callbacks, while incoming webhooks push messages into channels on demand." - Hookdeck guide to Slack webhooks + +That bidirectional flow matters. Your dashboard can display team activity and trigger actions based on what it sees, all from a single Python codebase. + +## Why Python Developers Choose Reflex for Slack Dashboards + +[Python developers building Slack dashboards](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) face a familiar problem: the moment you add a frontend, you're splitting your codebase. React handles the UI, Python handles the logic, and you spend time maintaining the layer between them. Reflex collapses that split. Your Slack event handlers, channel data processing, and message posting logic all live in one Python file. + +The Slack Python SDK, available via PyPI, requires Python 3.7 and above. Because Reflex runs on Python 3.10+, the two fit naturally. You call the SDK directly inside Reflex event handlers, and the framework pushes state updates to the browser over WebSockets automatically. No polling, no client-side fetch loops. When a Slack event arrives, your handler updates state and the UI reflects it. + +That real-time behavior matters for dashboards in particular. If you're tracking message volume or watching for keyword alerts, you want the dashboard to update as events happen. [Reflex's background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) handle long-running Slack API calls without blocking the UI, so a slow paginated fetch doesn't freeze your activity feed while it runs. + +On the component side, Reflex's 60+ [built-in components](https://reflex.dev/blog/custom-components/) cover what most Slack dashboards actually need: data tables for user activity, line charts for message trends, and list views for channel feeds. Teams compose these directly in Python instead of pulling in a separate charting library or maintaining a standalone frontend codebase. + +## Connecting Slack to Your Reflex App + +Getting Slack connected to a Reflex app starts with the `slack_sdk` package, which is [available on PyPI](https://pypi.org/project/slack-sdk/) and installs cleanly into any Python environment. Since Reflex already runs on Python 3.10+, there's no version juggling required. + +### Setting Up Credentials + +Reflex's project-level integration configuration is where the real time savings come in. Instead of wiring bot tokens and OAuth credentials into each individual app, you configure them once at the project level. Every dashboard in that project inherits those credentials automatically. If you're running multiple Slack dashboards across teams or workspaces, you skip repeated OAuth flows entirely. + +What you'll need from the Slack side: + +- A bot token (xoxb-...) with the appropriate OAuth scopes for your specific use case, such as reading channel history or posting messages + +- An Events API endpoint URL pointing to your Reflex app's API route so Slack knows where to send event payloads + +- A signing secret to verify that incoming requests actually originate from Slack and not an outside source + +### Handling Events and Posting Messages + +Once credentials are in place, the Slack Web API client lives directly inside your Reflex event handlers. An incoming Slack event hits your API route, the handler processes the payload, updates your app state, and the UI reflects the change over WebSockets thanks to [Reflex's architecture](https://reflex.dev/blog/reflex-architecture/). No middleware service sitting between Slack and your app. + +Posting messages back into Slack follows the same pattern. Your handler calls the Web API client, passes the channel ID and message content, and Slack delivers it. Because background tasks in Reflex run asynchronously, heavy API calls like paginated channel history fetches run without blocking your dashboard UI. + +Once your integration is working locally, [deploying is a single command](https://reflex.dev/hosting/) that handles infrastructure provisioning, so your Slack endpoints go live without manual server configuration. + +## Key Dashboard Components for Slack Data + +Slack's API returns structured JSON for every event type, which maps cleanly to a component-based UI. The real decision is matching each data shape to the right component so updates stay automatic and state stays consistent. + +### Message and Event Display Components + +Computed vars do the heavy lifting here. When a new Slack event arrives and updates your app state, computed vars automatically recalculate values like message counts per channel or active user totals, with no manual refresh logic required. This is where WebSocket-based state sync pays off: your channel feed, stat cards, and data tables all react to the same state object, so one incoming event can update multiple components at once. + +### Tables for Slack Analytics + +| Component Type | Slack Data Use Case | Reflex Component | Update Pattern | +|---|---|---|---| +| Message feed | Real-time channel activity | rx.data_table | WebSocket push | +| User metrics | Active members by channel | rx.stat | Computed var | +| Event log | Audit trail for workspace | rx.table | Event handler | +| Channel list | Workspace channel directory | rx.select | API call | + +For message feeds, ``[rx.data_table](https://reflex.dev/blog/using-table-component/) handles paginated Slack history well since it accepts a list of Python dicts directly. User metrics fit `rx.stat`, which displays a labeled number cleanly, useful for showing daily active members or messages sent this week. Audit logs belong in `rx.table` where you control row display precisely. All of these pull from the same Python state class, so there is no data synchronization work needed between components. + +## Deploying Your Slack Dashboard to Production + +Deploying with Reflex packages your entire Slack integration as one unit. Event handlers, bot token logic, API call routing, and the frontend all ship together with no separate frontend pipeline to configure or backend service to wire up independently. + +### Deployment Architecture Considerations + +Reflex Cloud handles HTTPS termination automatically, so your Slack Events API callback URL is production-ready the moment deployment completes. Slack's Events API [requires a 3-second response window](https://hookdeck.com/webhooks/platforms/guide-to-slack-webhooks-features-and-best-practices), HMAC signature verification, and idempotent retry handling. Reflex's API routes handle the response timing, and background tasks keep webhook acknowledgment fast even when your processing logic is heavy. + +For [self-hosted deployments](https://reflex.dev/blog/self-hosting-reflex-with-docker/), Reflex runs inside your own network boundary so Slack webhook handlers and data transformations never leave your infrastructure. + +### Enterprise Slack Integration Requirements + +Managing credentials across environments is straightforward using Reflex's config system alongside GitHub Actions or GitLab CI. Store your bot token and signing secret as environment variables in your CI pipeline, and each deployment pulls the correct credentials per environment automatically. + +[VPC deployment options](https://reflex.dev/blog/on-premises-deployment/) keep Slack event data within controlled network boundaries, which matters when webhook payloads touch sensitive internal data. Combined with RBAC across the dashboard itself, that gives enterprise teams access control at the application layer and network-level isolation underneath. + +## FAQ + +### Can I build a Slack dashboard without JavaScript? + +Yes. Reflex handles both frontend and backend in pure Python, so you build the entire Slack integration (event handlers, message posting, and UI components) without writing any JavaScript. The framework manages WebSocket connections and state sync automatically. + +### What's the fastest way to connect Slack's API to a Python dashboard? + +Install the `slack_sdk` package from PyPI, configure your bot token and signing secret at the project level in Reflex, then call Slack's Web API directly inside your event handlers. Reflex's WebSocket-based state sync pushes updates to the browser automatically when Slack events arrive. + +### How do I handle Slack's 3-second webhook response requirement? + +Reflex's API routes acknowledge Slack webhooks fast enough to meet the 3-second window, while background tasks process heavy logic asynchronously. This pattern keeps your webhook handler responsive even when you're fetching paginated channel history or updating multiple components. + +### Reflex vs Streamlit for building a Slack dashboard? + +Streamlit's script rerun model breaks under real-time Slack events: every incoming message triggers a full script re-execution, causing memory leaks and slowdowns. Reflex uses event-based state updates, so Slack events update only the affected components without re-running your entire app. + +### What Slack data works best in a real-time dashboard? + +Message volume per channel, active user counts, response time trends, and keyword alerts all map cleanly to Reflex components. The Events API pushes workspace activity to your app in real-time, and computed vars automatically recalculate metrics like daily active members when new events arrive. diff --git a/blog/build-fhir-api-dashboard-python.md b/blog/build-fhir-api-dashboard-python.md new file mode 100644 index 000000000..9867ad0f1 --- /dev/null +++ b/blog/build-fhir-api-dashboard-python.md @@ -0,0 +1,162 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With FHIR API in 2026" +title_tag: "Build FHIR API Dashboard 2026" +description: "Learn how to build a FHIR API dashboard with Python in April 2026. Complete tutorial covering authentication, data visualization, and HIPAA compliance." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "FHIR dashboard Python, FHIR API dashboard, healthcare dashboard, clinical data dashboard, HL7 FHIR Python" + } +] +faq: [ + {"question": "Can I build a FHIR dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full FHIR API integrations in pure Python, from OAuth handlers to clinical data visualization. Your entire stack stays in Python, which means security teams can audit patient data flows and compliance logic in one codebase instead of tracing behavior across split frontend and backend architectures."}, + {"question": "What's the fastest way to connect a FHIR API to a Python dashboard?", "answer": "Install `requests` or `httpx` via pip, then define your FHIR server endpoint and credentials once at the project level in Reflex. Event handlers fire on user interaction or page load to query patient resources, observations, or medication lists. The RESTful integration pattern works the same way you'd call any JSON API from Python."}, + {"question": "How do I visualize FHIR Observation resources in real time?", "answer": "Reflex's computed variables recalculate automatically when underlying FHIR data changes, pushing updates to the UI without manual DOM manipulation. Map Observation resources to time-series charts using the built-in recharts components. Clinical teams see current vital signs and lab values on every page load without refresh loops or polling hacks."}, + {"question": "FHIR dashboard Streamlit vs Reflex for healthcare apps?", "answer": "Streamlit's script rerun model causes memory leaks and slowdowns under clinical load, and it has no built-in authentication or role-based access control. Global Ultrasound Institute rejected Streamlit as \"too unprofessional for physician-facing interfaces.\" Reflex gives you event-based state management, native OAuth integration, and HIPAA-compliant deployment options that healthcare IT teams can actually audit."}, + {"question": "When should I deploy a FHIR dashboard on-premises instead of cloud?", "answer": "If your healthcare organization requires full infrastructure control for HIPAA audit requirements or needs to keep patient data within your own network boundary, self-host via Reflex's Helm chart orchestration on Kubernetes. This fits into the GitOps change control processes most healthcare IT teams already use, and security teams can verify that FHIR data never leaves your VPC."}, + {"question": "What FHIR resources can I display in a Python dashboard?", "answer": "Common FHIR resources for dashboards include Patient for demographics, Observation for vital signs and lab values, MedicationRequest for prescriptions, Encounter for appointments, and DiagnosticReport for lab results. Each resource type maps to specific UI components like data tables for patient directories or time-series charts for clinical measurements."}, + {"question": "Do I need to know React to build a FHIR dashboard with Reflex?", "answer": "No, you write everything in Python. Reflex handles the React rendering internally, and while you can optionally wrap React components for specialized medical UI libraries, your entire FHIR API integration and dashboard logic stays in pure Python without writing any JavaScript."}, + {"question": "How does OAuth 2.0 authentication work for FHIR APIs in Reflex?", "answer": "Reflex event handlers manage the complete OAuth lifecycle on the backend in Python, including token requests, refresh logic, and FHIR scope validation. This keeps authentication code auditable alongside your clinical data processing rules, supporting HIPAA compliance documentation without splitting security logic across frontend and backend."}, + {"question": "What's the difference between FHIR R4 and earlier versions for dashboard developers?", "answer": "FHIR R4 is the version becoming the baseline regulatory requirement by 2026 for healthcare IT systems in the United States. It provides standardized access to patient demographics, medications, lab results, and clinical observations through RESTful APIs, making healthcare data portable across systems."}, + {"question": "Can I filter and search patient data in a FHIR dashboard?", "answer": "Yes, Reflex's sortable data tables with filters work directly with FHIR Patient resources for building patient directories and search interfaces. You define the queries as event handlers that fire on user interaction, keeping the filtering logic in Python rather than client-side JavaScript."}, + {"question": "How do I handle FHIR data from multiple EHR systems in one dashboard?", "answer": "Reflex's project-level integration configuration lets you define multiple FHIR server endpoints and credentials once, then share them across every dashboard in the same project. This eliminates per-app reconfiguration and credential sprawl when connecting to different EHR systems."}, + {"question": "What monitoring capabilities exist for FHIR dashboards in production?", "answer": "Reflex includes built-in monitoring that tracks FHIR server response times and error rates without additional instrumentation. This helps clinical IT teams identify API performance issues and maintain service levels for care teams relying on real-time patient data."}, + {"question": "Can I build patient-facing portals and internal clinical dashboards with the same FHIR integration?", "answer": "Yes, FHIR clients span different app types that all consume the same underlying FHIR resources. You can deploy hybrid architectures with frontend on cloud for patient portal access while keeping backend clinical data processing on-premises, protecting internal services while providing public access."}, + {"question": "What compliance documentation does a FHIR dashboard need for HIPAA?", "answer": "HIPAA safeguards include encryption in transit and at rest, role-based access controls, and audit logging. Because Reflex keeps authentication and data processing in Python, security teams can audit the complete patient data flow in one codebase, creating the audit trail needed for compliance documentation."}, + {"question": "How do I display medication lists from FHIR MedicationRequest resources?", "answer": "Map MedicationRequest resources to stat cards for overview counts and list components for detailed prescription views. Reflex's built-in components handle the rendering while your Python event handlers query the FHIR API for active prescriptions and medication summaries."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- FHIR R4 API compliance is standard in 2026, giving developers access to patient demographics, medications, and lab results. + +- Reflex keeps FHIR dashboards in pure Python, letting clinical engineers read authentication and data logic without JavaScript. + +- Built-in components map directly to FHIR resources: data tables for Patient directories, time-series charts for Observations. + +- Deploy with VPC or on-premises Kubernetes to meet HIPAA requirements while maintaining audit logs and access controls. + +- Reflex is a full-stack Python framework that builds production web apps without JavaScript, used by 40% of Fortune 500 companies. + +## What You Can Build: FHIR API Dashboard Overview + +FHIR is the standard that finally made healthcare data portable. It gives developers granular access to specific patient data elements: demographics, allergies, medication lists, lab results, and clinical observations. By 2026, FHIR R4 API compliance is a baseline regulatory expectation for virtually every major healthcare IT system operating in the United States. + +What does that mean for builders? The API layer is largely solved. The harder problem is turning that data into something clinicians, administrators, and compliance teams can actually use. + +A FHIR API dashboard can serve several distinct audiences: + +- Patient monitoring interfaces that track patient vitals and medication adherence in real time, giving care teams an immediate view of patient status without digging through raw records. + +- Provider analytics showing appointment volumes and clinical quality measures to support performance reviews and care coordination decisions. + +- Compliance dashboards surfacing prior authorization metrics and audit logs so teams can respond to regulatory inquiries quickly. + +- Population health views that aggregate outcomes across patient cohorts, useful for identifying gaps in care at scale. + +FHIR clients also span a wide range of app types. Clinical dashboards, mobile patient apps, and analytics jobs all consume the same underlying FHIR resources, just with different presentation needs. For healthcare organizations already running Python for data science and ML work, building the dashboard layer in Python too with [Reflex AI](https://reflex.dev/use-cases/healthcare/) represents a meaningful reduction in complexity. + +## Why Python Developers Choose Reflex for FHIR API Dashboards + +Healthcare teams building FHIR dashboards run into the same wall repeatedly: the people who understand patient workflows and clinical data models are Python engineers, not JavaScript developers. [Reflex](https://reflex.dev/open-source/) removes that bottleneck entirely by keeping the entire stack in Python. Every FHIR API call, state transformation, and UI component lives in one codebase that clinical engineers can actually read. + +That matters more in healthcare than almost any other domain. When a dashboard surfaces unexpected lab values or breaks a compliance view, you need your team to open the code and understand it immediately. Python readability becomes a business requirement, not a developer preference. + +A few reasons this works well for FHIR: + +- Reflex's 60+ built-in components cover tables, charts, and stat cards that map directly to common FHIR resource views like patient lists, observation trends, and medication summaries, and [Reflex templates](https://reflex.dev/templates/) accelerate development. + +- React component wrapping lets you pull in specialized medical UI libraries when needed, without abandoning Python for the rest of the app. + +- On-premises and VPC deployment options satisfy the infrastructure requirements most healthcare organizations face under HIPAA. + +- Authentication, role-based access control, and audit logging integrate with standard Python security patterns, so compliance is built into the architecture from the start instead of bolted on afterward. + +Unlike code generation tools that output throwaway JavaScript, Reflex produces maintainable Python code that security teams can audit and version control alongside clinical logic. + +## Connecting FHIR API to Your Reflex App + +FHIR uses RESTful APIs with JSON and XML formats, which means connecting to a FHIR server from Reflex is straightforward Python work. Libraries like `requests` or `httpx` install via pip and slot directly into Reflex's backend state classes, where you [define resource queries](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) as event handlers that fire on user interaction or page load. + +### RESTful Integration Pattern + +[Reflex's project-level integration configuration](https://reflex.dev/overview/) lets you define your FHIR server endpoint and credentials once, then share them across every dashboard in the same project. For healthcare teams managing connections to multiple EHR systems, that centralization matters. No per-app reconfiguration, no credential sprawl across different codebases. + +### Authentication and Security + +Systems verify identity using OAuth 2.0 and token-based authentication, and FHIR scopes control exactly which patient resources a given application can read or write. Reflex event handlers manage the full OAuth lifecycle on the backend: token requests, refresh logic, and scope validation all live in Python. Security teams can audit that logic alongside your clinical data processing rules in one place, without tracing authentication behavior across a split frontend and backend architecture. That audit trail supports HIPAA compliance documentation without additional instrumentation.[^1] + +[^1]: [FHIR RESTful API interoperability guide](https://www.clindcast.com/healthcare-api-interoperability-and-fhir-guide-2026/) + +## Key Dashboard Components for FHIR API Data + +Each FHIR resource type has a natural UI counterpart. The key is knowing which component maps to which clinical data structure so you avoid rebuilding the same views repeatedly. + +### Resource Visualization Patterns + +A Patient resource holds demographics and identifiers, an Observation captures clinical measurements like blood pressure or lab values, and a MedicationRequest tracks prescriptions. Reflex's component library covers these patterns directly with [sortable data tables](https://reflex.dev/blog/using-table-component/), recharts-powered time-series graphs, and stat cards that surface counts at a glance. Here is how the mapping shakes out:[^1] + +| FHIR Resource | Dashboard Component | Use Case | +|---|---|---| +| Patient | Data table with filters | Patient directory and search | +| Observation | Time-series chart | Patient vitals monitoring | +| MedicationRequest | Stat card and list | Active prescriptions overview | +| Encounter | Calendar view | Appointment scheduling | +| DiagnosticReport | Document viewer | Lab results display | + +### Real-Time Data Updates + +FHIR APIs give you up-to-date patient information accessible from a single dashboard, which makes real-time UI behavior worth getting right.[^2] Computed variables recalculate automatically when underlying FHIR data changes, pushing updates to the UI without manual DOM manipulation. Clinical teams get current patient context on every page load, and care workflows stay uninterrupted. + +[^1]: [FHIR API integration guide for 2026](https://www.dogtownmedia.com/fhir-api-integration-in-mobile-app-development-the-complete-guide-for-businesses-in-2026/) +[^2]: [FHIR APIs and EHR data exchange overview](https://relevant.software/blog/fhir-apis/) + +## Deploying Your FHIR API Dashboard to Production + +Getting your FHIR dashboard into production requires careful attention to both infrastructure and compliance. [Reflex's quick-start deployment](https://reflex.dev/hosting/) wraps your entire FHIR dashboard, including OAuth handlers and clinical data processing logic, into a single pipeline with no separate frontend and backend build artifacts to coordinate. + +### Deployment Architecture + +Multi-region deployment reduces latency for clinical staff across hospital locations, while [built-in monitoring](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) tracks FHIR server response times and error rates without additional instrumentation. + +### Compliance and Enterprise Requirements + +Security mechanisms protecting patient data include encryption in transit and at rest, role-based access controls, audit logging, and [HIPAA safeguards](https://www.clindcast.com/healthcare-api-interoperability-and-fhir-guide-2026/). Healthcare organizations can also self-host via Helm chart orchestration on Kubernetes, fitting naturally into the GitOps change control processes most healthcare IT teams already use. + +| Deployment Environment | Use Case | Compliance Benefit | +|---|---|---| +| Reflex Cloud (VPC) | Hospital dashboard with EHR integration | Data stays within healthcare network boundary | +| On-premises (Kubernetes) | Multi-facility health system | Full infrastructure control for audit requirements | +| Hybrid (frontend cloud, backend on-prem) | Patient portal with internal clinical data | Public access with protected backend services | + +## FAQ + +### Can I build a FHIR dashboard without JavaScript? + +Yes. Reflex lets you build full FHIR API integrations in pure Python, from OAuth handlers to clinical data visualization. Your entire stack stays in Python, which means security teams can audit patient data flows and compliance logic in one codebase instead of tracing behavior across split frontend and backend architectures. + +### What's the fastest way to connect a FHIR API to a Python dashboard? + +Install `requests` or `httpx` via pip, then define your FHIR server endpoint and credentials once at the project level in Reflex. Event handlers fire on user interaction or page load to query patient resources, observations, or medication lists. The RESTful integration pattern works the same way you'd call any JSON API from Python. + +### How do I visualize FHIR Observation resources in real time? + +Reflex's computed variables recalculate automatically when underlying FHIR data changes, pushing updates to the UI without manual DOM manipulation. Map Observation resources to time-series charts using the built-in recharts components. Clinical teams see current patient vitals and lab values on every page load without refresh loops or polling hacks. + +### FHIR dashboard Streamlit vs Reflex for healthcare apps? + +Streamlit's script rerun model causes memory leaks and slowdowns under clinical load, and it has no built-in authentication or role-based access control. Global Ultrasound Institute rejected Streamlit as "too unprofessional for physician-facing interfaces." Reflex gives you event-based state management, native OAuth integration, and HIPAA-compliant deployment options that healthcare IT teams can actually audit. + +### When should I deploy a FHIR dashboard on-premises instead of cloud? + +If your healthcare organization requires full infrastructure control for HIPAA audit requirements or needs to keep patient data within your own network boundary, self-host via Reflex's Helm chart orchestration on Kubernetes. This fits into the GitOps change control processes most healthcare IT teams already use, and security teams can verify that FHIR data never leaves your VPC. diff --git a/blog/build-python-web-app-aws-s3.md b/blog/build-python-web-app-aws-s3.md new file mode 100644 index 000000000..71b62dc78 --- /dev/null +++ b/blog/build-python-web-app-aws-s3.md @@ -0,0 +1,160 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With AWS (S3) in 2026" +title_tag: "Build Python Web App With AWS S3 2026" +description: "Learn how to build a Python web app with AWS S3 in April 2026. File uploads, downloads, and bucket management in pure Python without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "AWS S3 Python app, S3 web app, file upload Python, AWS integration Python, cloud storage app, S3 Python tutorial" + } +] +faq: [ + {"question": "Can I build a Python web app with AWS (S3) without JavaScript?", "answer": "Yes. Reflex lets you build full-stack web apps with S3 integration in pure Python—no JavaScript required. You import boto3 directly into your Reflex State class, call S3 methods inside event handlers, and connect the results to Reflex's built-in UI components like `rx.upload` and `rx.data_table`."}, + {"question": "How do I authenticate my Python app with AWS S3?", "answer": "boto3 searches for credentials in this order: environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`), the shared credentials file (`~/.aws/credentials`), the AWS config file, and IAM roles attached to compute instances. For local development, use environment variables. For production deployments on Reflex Cloud, pass credentials as environment variables at deploy time to keep secrets out of source control."}, + {"question": "What's the fastest way to deploy a Python web app with S3 to production?", "answer": "Run `reflex deploy` from your project directory. Reflex Cloud provisions infrastructure automatically, handles multi-region scaling, and supports CI/CD integration through GitHub Actions or GitLab CI. The entire deployment process requires no server configuration—just pass your AWS credentials as environment variables and the same Python code that runs locally deploys to a live URL."}, + {"question": "Reflex vs Streamlit for building S3 file managers?", "answer": "Streamlit's script rerun model re-executes your entire application on every interaction, causing performance issues with S3 operations and making state management unreliable for multi-step upload workflows. Reflex uses event-based handlers that update only the relevant state variables, so S3 calls run exactly when needed and UI updates happen automatically without full page reloads."}, + {"question": "Can I deploy a Python S3 app in my own VPC for compliance?", "answer": "Yes. Reflex supports VPC deployment and on-premises Flexgen options without changing your Python codebase. The same app that runs locally deploys into your controlled network boundary with the same RBAC, audit logging, and security model—critical for healthcare records, financial documents, and regulated datasets that can't live on shared cloud infrastructure."}, + {"question": "How do presigned URLs work for S3 file downloads in Reflex?", "answer": "Presigned URLs are generated by calling `s3_client.generate_presigned_url()` inside a Reflex event handler, which creates a temporary URL with controlled expiration. You store this URL in a state variable and render it as an `rx.link` component, keeping all access logic on the Python backend while providing secure, time-limited download access to users."}, + {"question": "What S3 operations can I perform from a Reflex app?", "answer": "You can perform full CRUD operations on S3 through boto3 methods in Reflex event handlers: upload files with `upload_fileobj()`, list bucket contents with `list_objects_v2()`, generate download URLs with `generate_presigned_url()`, and delete objects with `delete_object()`. Each operation updates your State class variables, which automatically refresh the UI."}, + {"question": "Do I need to write separate backend and frontend code for S3 file handling?", "answer": "No. Reflex eliminates the need for separate backend and frontend codebases—you write the entire app in Python, including the file upload UI, S3 connection logic, and state management. The framework handles the connection between your boto3 calls and UI components automatically."}, + {"question": "Which Reflex components are best for building S3 file managers?", "answer": "The `rx.upload` component handles drag-and-drop and click-to-browse file selection, while `rx.data_table` displays S3 objects with their metadata. These components connect directly to your State class, so S3 data flows from boto3 calls to UI rendering without additional glue code."}, + {"question": "How does Reflex handle large file uploads to S3?", "answer": "For large uploads, Reflex supports background tasks that prevent blocking the UI during file transfer. You call `s3_client.upload_fileobj()` inside an event handler, and state variables track upload progress and surface success or error messages automatically."}, + {"question": "Can I use IAM roles instead of access keys for S3 authentication?", "answer": "Yes. When deploying on AWS infrastructure like EC2, Lambda, or ECS, boto3 automatically uses IAM roles attached to the compute instance. This is the cleanest production option since no access keys ever touch your codebase or environment variables."}, + {"question": "What happens to the UI when S3 data changes after an upload or delete?", "answer": "Updating the state variable that holds your S3 object list is enough—the `rx.data_table` component re-renders automatically with the new data. There's no need for manual DOM updates, polling loops, or page reloads."}, + {"question": "How do I keep AWS credentials secure when deploying to Reflex Cloud?", "answer": "Pass `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` as environment variables at deploy time rather than hardcoding them in your source code. This keeps secrets out of your repository entirely while making them available to your deployed application."}, + {"question": "Can Reflex apps connect to S3-compatible storage like MinIO or DigitalOcean Spaces?", "answer": "Yes. Since Reflex uses boto3 for S3 operations, you can configure the client to connect to any S3-compatible storage service by specifying a custom endpoint URL when initializing the boto3 client."}, + {"question": "What types of applications are best suited for combining Reflex with S3?", "answer": "Internal document portals, media libraries, dataset managers for data science teams, user-generated content platforms, and any application requiring file storage with controlled access. The pattern works especially well for teams that need production-grade file handling without maintaining separate frontend and backend codebases."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Build full-stack S3 file managers in pure Python with drag-and-drop uploads, presigned downloads, and live bucket browsing without any JavaScript + +- Reflex integrates boto3 directly into event handlers, turning S3 operations into standard Python functions that update UI state automatically + +- Deploy with environment variables for AWS credentials and VPC options for industries with compliance requirements needing on-premises file storage + +- Reflex is an open-source Python framework for building production web apps entirely in Python, trusted by 40% of Fortune 500 companies + +## Why Python Developers Are Building Web Apps With AWS (S3) in 2026 + +S3 has become the default object storage layer for web apps, and for good reason. It handles unlimited scale, works from anywhere, and covers nearly every file storage use case: user uploads, media libraries, log archives, backups, static assets, data lakes. If your app touches files, S3 is probably in the architecture. + +The problem is wiring it into a web interface. Traditionally, that meant writing a Python backend, then a separate JavaScript frontend, then figuring out how presigned URLs flow between them. For data scientists or backend developers, that last step is where projects stall. + +> + +"With Panel it became hard to maintain and extend. Reflex is clean." - Delta Global Head of Quant + +That friction is exactly what Reflex removes. With Reflex, you write the entire app in Python: the file upload UI, the S3 connection logic, the state that tracks what's been uploaded. No JavaScript, no separate frontend codebase, no context switching between languages. + +For Python developers who want production-grade file handling without learning React, [Reflex makes S3 integration](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) a backend problem, which is exactly where it belongs. + +## What You'll Build: A Python Web App Powered by AWS (S3) + +By the end of this guide, you'll have a working file manager where users can upload documents, images, or datasets directly to an S3 bucket, browse uploaded files in a table view, download any file through a presigned URL, and delete objects on demand. Full CRUD, all from a Python web app. + +The core features break down like this: + +- Upload files through a drag-and-drop interface built with Reflex's built-in file upload handling, so users never touch a separate storage console + +- List bucket contents dynamically, with each file showing its name, size, and upload date pulled live from S3 + +- Generate presigned download URLs so files stay private but remain accessible to the right users on demand + +- Delete objects directly from the UI, with state that updates instantly after each operation without a page reload + +Every interaction maps to a Reflex event handler (a Python function that calls the AWS SDK, updates application state, and triggers a UI refresh automatically). No polling, no manual DOM updates, no glue code between frontend and backend. + +This pattern covers the most common S3 use case in production apps: user-generated content storage with controlled access. Check out our [Reflex templates](https://reflex.dev/templates/) for more examples. Whether you're building an internal document portal, a media library, or a dataset manager for a data science team, this foundation transfers across projects. + +## Connecting AWS (S3) to Your Reflex App + +Reflex supports AWS as an integration in its ecosystem, but the actual S3 connection runs through boto3, Amazon's official Python SDK. Since any Python library can be imported directly into Reflex event handlers, wiring up S3 is less framework configuration and more standard Python setup. + +### Setting Up Boto3 Integration + +Start by installing boto3 into your project environment with pip. Once installed, you can import it anywhere in your Reflex app, including inside a State class where your event handlers live. The S3 client initializes like any other boto3 client. You pass in a region and optionally explicit credentials, and from there every S3 operation (upload, list, delete, presign) is a method call. + +boto3 searches for credentials in this order (see [boto3 production best practices](https://medium.com/@u.mair/12-best-practices-to-keep-your-boto3-scripts-from-breaking-in-production-f0f726bdfba0) for more details): + +- Environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`) are the fastest way to get running locally without touching any config files. + +- Shared credentials file (`~/.aws/credentials`) works well for developers who manage multiple AWS accounts on the same machine. + +- AWS config file serves as a fallback when the credentials file is absent. + +- IAM roles attached to the compute instance (EC2, Lambda, ECS) are the cleanest production option since no keys ever touch your codebase. + +### Credential Management and Project Configuration + +Because Reflex's project-level integration configuration shares context across all apps in a project, you only need to set your AWS credentials once. Reference them from environment variables inside your State class, and every event handler in the application can access the same authenticated S3 client without redundant setup. + +For Reflex deployments outside AWS, pass credentials through environment variables at deploy time to keep secrets out of source control. + +## Building the UI Around AWS (S3) in Pure Python + +Reflex ships with 60+ built-in components (plus [custom components](https://reflex.dev/blog/custom-components/) when you need them), and two of them do most of the heavy lifting here: `rx.upload` for capturing files and `rx.data_table` for displaying S3 objects. Both connect directly to your State class, so no glue code sits between the UI and your boto3 calls. + +### File Upload Component and S3 Put Operations + +The `rx.upload` component handles drag-and-drop and click-to-browse out of the box. When a user selects a file, the upload triggers an event handler where you call `s3_client.upload_fileobj()` directly. For large uploads, consider using [background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/). State variables track whether the upload is in progress and surface success or error messages back to the UI automatically. The entire flow, from capture to upload to feedback, stays in Python. + +### Displaying S3 Objects in Interactive Tables + +Call `s3_client.list_objects_v2()` inside an event handler, store the results as a Python list in your State class, and pass that list to an `rx.data_table`. When S3 data changes after an upload or delete, updating the state variable is enough. The table updates automatically with no manual DOM updates and no polling loop. + +| Operation | Boto3 Method | Reflex Pattern | UI Component | +|---|---|---|---| +| Upload file | `upload_fileobj()` | Event handler updates state | `rx.upload` | +| List objects | `list_objects_v2()` | State var holds list | `rx.data_table` | +| Download file | `generate_presigned_url()` | Returns temporary URL | `rx.link` | +| Delete object | `delete_object()` | Event handler refreshes list | `rx.button` | + +### Presigned URL Generation for Secure Downloads + +For downloads, call `s3_client.generate_presigned_url()` inside an event handler, store the result in a state variable, and render it as an `rx.link`. The URL expires on a schedule you control, and all the access logic stays on the Python backend, never exposed to the client. For security considerations, review [AWS presigned URL best practices](https://docs.aws.amazon.com/prescriptive-guidance/latest/presigned-url-best-practices/overview.html). + +## Deploying Your AWS (S3) App to Production + +Once your app works locally, shipping it requires minimal effort. [Reflex Cloud](https://reflex.dev/hosting/) handles infrastructure provisioning automatically, so there's no server configuration standing between your Python code and a live URL. + +### Single Command Deployment with Reflex Cloud + +AWS credentials never belong in source control. Reflex Cloud lets you pass `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` as environment variables at deploy time, keeping secrets out of your repository entirely. For self-hosting needs, see our guide on [self-hosting Reflex with Docker](https://reflex.dev/blog/self-hosting-reflex-with-docker/). If your S3 buckets span multiple AWS regions to serve users across geographies, Reflex Cloud's multi-region deployment capability keeps latency low by running your app close to where requests originate. CI/CD integration through GitHub Actions or GitLab CI fits into any existing pipeline. + +### VPC and On-Premises Options for Compliance + +Not every S3 app can live on a shared cloud host. [Healthcare records](https://reflex.dev/use-cases/healthcare/), financial documents, and datasets with compliance requirements often require deployment within a controlled network boundary. Reflex's VPC deployment and [on-premises Flexgen options](https://reflex.dev/blog/on-premises-deployment/) cover these requirements without changing your Python codebase. The same app that runs locally deploys into your own infrastructure, with the same RBAC, audit logging, and security model intact. For teams in finance, healthcare, or government, this is what makes Reflex viable where other Python web frameworks fall short. More on self-hosting options here. + +## FAQ + +### Can I build a Python web app with AWS (S3) without JavaScript? + +Yes. Reflex lets you build full-stack web apps with S3 integration in pure Python with no JavaScript required. You import boto3 directly into your Reflex State class, call S3 methods inside event handlers, and connect the results to Reflex's built-in UI components like `rx.upload` and `rx.data_table`. + +### How do I authenticate my Python app with AWS S3? + +boto3 searches for credentials in this order: environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`), the shared credentials file (`~/.aws/credentials`), the AWS config file, and IAM roles attached to compute instances. For local development, use environment variables; for production deployments on Reflex Cloud, pass credentials as environment variables at deploy time to keep secrets out of source control. + +### What's the fastest way to deploy a Python web app with S3 to production? + +Run `reflex deploy` from your project directory. Reflex Cloud provisions infrastructure automatically, handles multi-region scaling, and supports CI/CD integration through GitHub Actions or GitLab CI. The entire deployment process requires no server configuration. + +### What's the main difference between Reflex and Streamlit for building S3 file managers? + +Streamlit's script rerun model re-executes your entire application on every interaction, causing performance issues with S3 operations and making state management unreliable for multi-step upload workflows. Reflex uses event-based handlers that update only the relevant state variables, so S3 calls run exactly when needed and UI updates happen automatically without full page reloads. + +### Can I deploy a Python S3 app in my own VPC for compliance? + +Yes. Reflex supports VPC deployment and on-premises Flexgen options without changing your Python codebase. The same app that runs locally deploys into your controlled network boundary with the same RBAC, audit logging, and security model. This is critical for healthcare records, financial documents, and datasets with compliance requirements that can't live on shared cloud infrastructure. diff --git a/blog/build-python-web-app-hubspot.md b/blog/build-python-web-app-hubspot.md new file mode 100644 index 000000000..ec463decb --- /dev/null +++ b/blog/build-python-web-app-hubspot.md @@ -0,0 +1,154 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With HubSpot in 2026" +title_tag: "Build Python Web App With HubSpot 2026" +description: "Learn to build Python web apps with HubSpot using Reflex and the HubSpot SDK. Create custom CRM dashboards without JavaScript in April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "HubSpot Python app, HubSpot API Python, CRM web app, HubSpot integration Python, sales app Python, marketing automation Python" + } +] +faq: [ + {"question": "Can I build a HubSpot web app without JavaScript?", "answer": "Yes. Reflex lets you build full HubSpot integrations entirely in Python, handling both the API connection and the user interface without writing any JavaScript. The HubSpot Python SDK integrates directly into your Reflex state class, so API calls and UI logic live in the same codebase."}, + {"question": "HubSpot integration with Reflex vs Streamlit?", "answer": "Reflex handles event-based interactions and real-time state updates that HubSpot integrations need, while Streamlit's script rerun model causes performance issues with live CRM data. Reflex gives you inline editing, filtered tables, and associated object displays without the memory leaks and inefficiencies that come with Streamlit's linear execution pattern."}, + {"question": "How do I connect my Reflex app to HubSpot's API?", "answer": "Install the HubSpot Python SDK via pip, then initialize the client inside your Reflex state class using a Private App Token stored as an environment variable. Reflex supports project-level integration configuration, so you set credentials once and all apps in the project inherit them automatically."}, + {"question": "What's the fastest way to deploy a HubSpot app in 2026?", "answer": "Build your app with Reflex and deploy with a single command. Store your HubSpot token as an environment secret, and the app goes live with multi-region support, auth controls, and RBAC built in."}, + {"question": "When should I build a custom HubSpot interface instead of using HubSpot's UI?", "answer": "If your team needs filtered views, custom workflows, or data combinations that HubSpot's interface doesn't support out of the box. Internal sales tools, lead-routing apps, and CRM dashboards that pull in external data sources are common use cases where a custom Python app saves hours of manual work each week."}, + {"question": "What HubSpot objects can I work with using the Python SDK in Reflex?", "answer": "The HubSpot Python SDK lets you work with contacts, companies, deals, tickets, and custom objects. Each object type has its own set of properties—for example, contacts include email, firstname, lastname, and phone, while deals cover dealname, amount, and dealstage for sales pipeline tracking."}, + {"question": "Do I need to use OAuth to connect to HubSpot's API?", "answer": "Not necessarily. While HubSpot retired API keys in 2022, you can use either OAuth or a Private App Token for authentication. Private App Tokens are simpler for internal tools and can be stored as environment variables that your Reflex app reads automatically."}, + {"question": "How does Reflex handle state updates when HubSpot data changes?", "answer": "Reflex uses a reactive state system that automatically re-renders UI components when state variables change. When a HubSpot API response arrives, it writes to a state variable and Reflex propagates that change to every component watching it, with no manual refresh logic or polling required."}, + {"question": "Can I edit HubSpot contact records directly from my Reflex app?", "answer": "Yes. You can build inline edit panels that update HubSpot contact properties without leaving the app. When a user edits a field, the event handler calls the HubSpot SDK to update the record, then refreshes the state variable so the UI updates automatically."}, + {"question": "What compliance features does Reflex offer for HubSpot integrations in regulated industries?", "answer": "Reflex supports VPC and on-premises hosting for regulated industries like finance and healthcare where customer data must stay within controlled infrastructure. It also includes auth controls and RBAC out of the box to meet enterprise compliance standards."}, + {"question": "How do I display associated company information alongside HubSpot contacts?", "answer": "The HubSpot SDK lets you retrieve associated objects in a single API call, so you can pull company data alongside contact records. In Reflex, that information can sit in the same table row since contact records are stored as Python lists of dictionaries that your table component reads directly."}, + {"question": "Can I filter HubSpot contacts by deal stage or owner in my Reflex app?", "answer": "Yes. Filtering triggers an event handler that calls the HubSpot SDK with updated query parameters, writes the response back to state, and Reflex automatically re-renders the affected table rows. The filter controls integrate directly into your Python codebase without requiring separate frontend logic."}, + {"question": "How long does it take to build a basic HubSpot contact dashboard with Reflex?", "answer": "You can create a searchable contact dashboard with inline editing in under 30 minutes. Reflex handles the UI rendering, state management, and real-time updates automatically, while the HubSpot Python SDK manages the data layer in the same Python file."}, + {"question": "Where should I store my HubSpot Private App Token in a Reflex project?", "answer": "Store your HubSpot Private App Token as an environment variable or environment secret so it never appears in your codebase. Reflex supports project-level integration configuration, meaning you set the credential once and every app in the project inherits it automatically."}, + {"question": "Does Reflex support multi-region deployment for HubSpot apps?", "answer": "Yes. Reflex offers multi-region deployment to keep latency low for teams pulling CRM data across different geographies. This works alongside auth controls, RBAC, and VPC support for enterprise-grade HubSpot integrations."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Build HubSpot web apps in pure Python without JavaScript using Reflex and the HubSpot SDK + +- Create searchable contact dashboards with inline editing in under 30 minutes + +- Deploy with VPC support for enterprise compliance in finance and healthcare + +- Reflex handles real-time state management between HubSpot APIs and your UI automatically + +## Why Python Developers Are Building Web Apps With HubSpot in 2026 + +HubSpot holds a goldmine of customer data. Contacts, deals, pipeline stages, activity logs. It's all there. But getting that data into a custom interface that your team actually wants to use? That's where things get frustrating fast. + +The typical workaround is a Python script. Pull from the HubSpot API, dump results into a spreadsheet, repeat. It works, barely, until someone needs a filter or a button or anything that resembles a real app. At that point, you're staring down a React project you didn't sign up for, or comparing Python web frameworks that can handle both frontend and backend. + +> + +HubSpot API integrations help create a complete view of the customer lifecycle, eliminating duplicate data entry and keeping records consistent across systems, but only if the interface connecting your team to that data is worth using. + +That's the gap Reflex fills. With Reflex, Python developers can build full-stack web apps without touching JavaScript. Your HubSpot integration lives in the same Python codebase as your UI, your state management, and your business logic. No frontend bottleneck. No context-switching between languages. + +In 2026, more Python teams are treating HubSpot as a live data source instead of a standalone tool. Whether you're building a custom CRM dashboard, a lead-routing app, or an internal sales tool, Reflex gives you [a clear path from API to app](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) without leaving Python. + +## What You'll Build: A Python Web App Powered by HubSpot + +The app you're building is a contact management dashboard that pulls HubSpot contact records into a searchable, filterable table your team can actually interact with. + +Here's what the finished app includes: + +- A searchable data table displaying HubSpot contacts with name, email, company, and lifecycle stage + +- Filter controls to segment contacts by deal stage, owner, or custom properties + +- An inline edit panel for updating contact properties without leaving the app + +- Associated company information surfaced alongside each contact record + +The HubSpot Python SDK handles the data layer. It gives you methods to create, retrieve, and update HubSpot objects, including contacts, deals, companies, and custom objects, all from Python. No third-party middleware, no manual HTTP wiring. + +Reflex handles everything else. State management, real-time UI updates, the data table display. It all lives in one Python file. When a user edits a contact field, the event handler fires, calls the SDK, and updates the UI. No JavaScript involved at any step. + +This is one of the most common patterns Python teams reach for when HubSpot's default interface no longer meets their needs. You can get started at [build.reflex.dev](https://build.reflex.dev/) and build from scratch. + +## Connecting HubSpot to Your Reflex App + +Before any UI gets built, you need a live connection between your Reflex app and HubSpot's API. + +### Installing the HubSpot Python SDK + +The official HubSpot Python SDK installs via pip like any other package. Once it's in your environment, it imports directly into your Reflex state class with no separate backend service required. + +Before you can make API calls, you'll need to [choose between OAuth and Private App tokens](https://trio.dev/hubspot-api/) for authentication, with Private App tokens being the simpler choice for internal tools. + +For credentials, HubSpot [retired API keys in 2022](https://trio.dev/hubspot-api/), so every integration now uses either OAuth or a Private App Token. Private App Tokens are the simpler path for internal tools. Store your token as an environment variable, then reference it from your Reflex state. Reflex supports project-level integration configuration, so you set the credential once and every app in the project inherits it automatically. + +### Calling HubSpot APIs from Reflex State + +The HubSpot client initializes inside your Reflex state class, which means API calls live right alongside your app logic. When a user triggers an action such as searching contacts, editing a field, or filtering by deal stage, a Reflex event handler fires, calls the SDK, and writes the response into a state variable. + +From there, Reflex's reactive system does the rest. Updated state variables automatically re-render the affected UI components. No manual refresh logic, no polling loop. The connection between your HubSpot data and your interface is direct. + +## Building the UI Around HubSpot in Pure Python + +With your HubSpot connection in place, the UI layer is where Reflex earns its keep. Every component, every event handler, every state update is written in Python. + +### Displaying Contact Data in Components + +Reflex's built-in component library covers the data table display you'd expect from [a CRM-style dashboard](https://reflex.dev/templates/admin-console-dashboard/). Contact records pulled from HubSpot live in a state variable, essentially a Python list of dictionaries that [your table component](https://reflex.dev/blog/using-table-component/) reads directly from. Your table component reads directly from that variable, so any change to state automatically reflects in the UI. + +Filtering by deal stage or owner triggers an event handler that calls the HubSpot SDK with updated query parameters, writes the response back to state, and lets Reflex re-render the affected rows. Associated company information can sit alongside each contact in the same table row, since the SDK lets you retrieve associated objects in a single API call. + +Here's a breakdown of the HubSpot CRM objects you'll work with and what each one covers: + +| HubSpot Object | Common Properties | Typical Use Case | +|---|---|---| +| Contacts | email, firstname, lastname, phone | Customer relationship tracking | +| Companies | name, domain, industry | Account management | +| Deals | dealname, amount, dealstage | Sales pipeline tracking | +| Tickets | subject, status, priority | Support case management | + +### Handling Real-Time Updates + +When a HubSpot API response arrives, Reflex's reactive state system propagates the change to every component watching that variable. No JavaScript event listeners. No manual DOM updates. The state management layer handles the entire data flow between your backend SDK calls and the frontend React components that Reflex compiles under the hood. + +Inline edits work the same way. A user changes a contact's lifecycle stage, the event handler updates HubSpot via the SDK, and the state variable refreshes. If you need to persist records locally between sessions, Reflex's built-in database layer connects with a single line of Python. + +## Deploying Your HubSpot App to Production + +Once your app is ready, [deploying takes a single command](https://reflex.dev/hosting/). Follow the deploy quick start to go live fast. + +Store your HubSpot Private App Token as [an environment secret](https://reflex.dev/blog/enterprise-ready-ai-app-builder/) so it never appears in your codebase. Multi-region deployment keeps latency low for teams pulling CRM data across different geographies. + +For [industries with strict compliance requirements](https://reflex.dev/use-cases/finance/) where customer data must stay within controlled infrastructure, Reflex supports VPC and on-premises hosting. Pair that with [auth controls and RBAC](https://reflex.dev/blog/on-premises-deployment/), and your HubSpot integration meets enterprise compliance standards out of the box. + +## FAQ + +### Can I build a HubSpot web app without JavaScript? + +Yes. Reflex lets you build full HubSpot integrations entirely in Python, handling both the API connection and the user interface without writing any JavaScript. The HubSpot Python SDK integrates directly into your Reflex state class, so API calls and UI logic live in the same codebase. + +### HubSpot integration with Reflex vs Streamlit? + +Reflex handles event-based interactions and real-time state updates that HubSpot integrations need, while Streamlit's script rerun model causes performance issues with live CRM data. Reflex gives you inline editing, filtered tables, and associated object displays without the memory leaks and inefficiencies that come with Streamlit's linear execution pattern. + +### How do I connect my Reflex app to HubSpot's API? + +Install the HubSpot Python SDK via pip, then initialize the client inside your Reflex state class using a Private App Token stored as an environment variable. Reflex supports project-level integration configuration, so you set credentials once and all apps in the project inherit them automatically. + +### What's the fastest way to deploy a HubSpot app in 2026? + +Build your app with Reflex and deploy with a single command. Store your HubSpot token as an environment secret, and the app goes live with multi-region support, auth controls, and RBAC built in. + +### When should I build a custom HubSpot interface instead of using HubSpot's UI? + +If your team needs filtered views, custom workflows, or data combinations that HubSpot's interface doesn't support out of the box. Internal sales tools, lead-routing apps, and CRM dashboards that pull in external data sources are common use cases where a custom Python app saves hours of manual work each week. diff --git a/blog/build-python-web-app-hugging-face.md b/blog/build-python-web-app-hugging-face.md new file mode 100644 index 000000000..103b0f1ed --- /dev/null +++ b/blog/build-python-web-app-hugging-face.md @@ -0,0 +1,151 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Hugging Face in 2026" +title_tag: "Build Python Web Apps With Hugging Face 2026" +description: "Learn how to build a Python web app with Hugging Face models in April 2026. Complete tutorial covering setup, deployment, and real-time inference." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Hugging Face Python app, ML model web app, transformers Python app, Hugging Face integration, NLP Python app, AI model app" + } +] +faq: [ + {"question": "Can I build a Hugging Face web app without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire web app, frontend and backend, in pure Python. Your UI components, state management, and Hugging Face model calls all live in the same Python codebase, with no JavaScript required."}, + {"question": "What's the difference between using Hugging Face Inference API vs loading models locally in a Python web app?", "answer": "The Inference API runs models on Hugging Face's infrastructure, making it faster to prototype and better for serverless deployments. Local loading with Transformers gives you lower latency and works better for private deployments or fine-tuned models, but requires managing your own compute resources."}, + {"question": "How do I handle real-time streaming from Hugging Face text generation models in a web interface?", "answer": "Reflex's WebSocket-based state sync pushes each token to the browser as it arrives from Hugging Face, updating the UI in real time without polling. You write a standard Python event handler that yields results progressively, and the frontend re-renders automatically with each chunk."}, + {"question": "When should I self-host my Hugging Face web app instead of using cloud deployment?", "answer": "Self-host when your Hugging Face models process sensitive data like healthcare records, financial documents, or private user content that can't leave your security perimeter. Reflex supports VPC and on-premises deployment, keeping model calls inside your compliance boundaries while maintaining the same Python codebase."}, + {"question": "What types of Hugging Face models can I integrate into a Python web app with Reflex?", "answer": "You can integrate any Hugging Face model task including text generation, text classification, image classification, question answering, image segmentation, and automatic speech recognition. All these tasks follow the same integration pattern: an input component, a backend event handler that calls the model, and an output component that re-renders when state changes."}, + {"question": "Do I need to manage separate API servers to connect Hugging Face models to my web app?", "answer": "No. Because Reflex's backend runs standard Python, your Hugging Face model calls live inside Reflex state event handlers right alongside your UI state, with no separate API server required."}, + {"question": "How do I store my Hugging Face API token securely in production?", "answer": "Store your Hugging Face token as an environment variable in Reflex Cloud rather than hardcoding it. Your event handlers can then read it at runtime through your app's configuration layer with no exposure in source control."}, + {"question": "What are the main advantages of using Reflex to build Hugging Face web apps compared to traditional web frameworks?", "answer": "Reflex lets Python developers build the entire app—frontend, backend, and ML logic—in a single Python codebase without learning JavaScript or React. This eliminates context-switching and the need for a split codebase, allowing your ML logic and web layer to communicate directly."}, + {"question": "How does Reflex handle state updates when a Hugging Face model returns results?", "answer": "Reflex uses WebSocket-based state sync to automatically update the UI whenever state changes. When your event handler receives a response from Hugging Face, Reflex triggers a re-render without requiring any additional code."}, + {"question": "Can I use custom or fine-tuned Hugging Face models in a Reflex web app?", "answer": "Yes. You can load custom or fine-tuned models directly into your Python environment using the Transformers library's pipeline() function, which works better for private deployments or models that aren't hosted publicly on Hugging Face."}, + {"question": "What performance optimizations should I implement for production Hugging Face web apps?", "answer": "Cache repeated inference results for identical inputs, set rate limits on event handlers to avoid API timeouts during traffic spikes, and consider using Hugging Face Dedicated Inference Endpoints for latency-sensitive workloads that need dedicated infrastructure."}, + {"question": "How do I display loading states while waiting for Hugging Face model responses?", "answer": "Control a loading boolean in your Reflex state by setting it to true before the inference call and false after. The UI automatically reacts by showing a spinner during inference and swapping in the result when it arrives."}, + {"question": "Can I deploy a Reflex Hugging Face app without managing infrastructure?", "answer": "Yes. Running 'reflex deploy' automatically handles infrastructure provisioning, multi-region scaling, and SSL through Reflex Cloud, allowing you to ship your app with a single command."}, + {"question": "What component types does Reflex provide for building Hugging Face model interfaces?", "answer": "Reflex provides input fields, text areas, file uploaders, and dropdowns that bind directly to state variables, plus a custom component library that gives you everything needed to build production-grade UIs without writing JavaScript."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build full-stack web apps with Hugging Face models in pure Python using Reflex. No JavaScript required. + +- Reflex handles real-time streaming from Hugging Face's Inference API through WebSocket-based state sync. + +- Deploy with `reflex deploy` in one command, with automatic secrets management and VPC options for compliance. + +- Reflex is an open-source Python framework that lets you build production web apps entirely in Python without learning frontend technologies. + +## Why Python Developers Are Building Web Apps With Hugging Face in 2026 + +By 2026, Hugging Face hosts [over 2 million models and 1 million](https://www.techaimag.com/latest-hugging-face-models/hugging-face-complete-guide-2026-models-datasets-development), with thousands of enterprises running it in production. That's not a research playground anymore. That's infrastructure. + +The problem is getting those models in front of users. Most Python developers have capable ML pipelines living entirely in Jupyter notebooks or CLI scripts. Turning that work into something a colleague, client, or customer can actually use requires a web interface, which historically meant learning JavaScript, React, and a separate frontend codebase. + +That's the gap. Python developers know the models. They don't want to context-switch into TypeScript to ship them. + +Reflex closes that gap by letting you [build full-stack apps in pure Python](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/). No JavaScript. No split codebase. You call a Hugging Face model in the same language you use to define the UI. State management, event handling, and real-time updates all stay in Python, which means your ML logic and your web layer can talk to each other without an API layer sitting between them. + +For Python developers who want to ship AI-powered web apps without becoming frontend engineers, that's the right setup in 2026. + +## What You'll Build: A Python Web App Powered by Hugging Face + +The app you're building is straightforward: a web interface where a user submits text, your backend sends it to a Hugging Face model, and the result appears in the UI in real time. The interaction loop is the same regardless of which model you pick: input comes in, the model processes it, output comes back, the UI updates. Once you build this once, switching to a different Hugging Face task is mostly just swapping the model call. + +For this walkthrough, text generation and classification are the primary anchors since they cover the widest range of real-world use cases. The integration pattern stays identical whether you're processing images, answering questions over documents, or running speech recognition. + +### Common Hugging Face Use Cases in Web Apps + +| Model Task | Input Type | Output Type | Common Use Cases | +|---|---|---|---| +| Text Generation | Text prompt | Generated text | Chatbots, content creation, code completion | +| Text Classification | Text input | Category labels | Sentiment analysis, content moderation, intent detection | +| Image Classification | Image file | Category labels | Product tagging, quality control, medical screening | +| Question Answering | Context + question | Answer text | Documentation search, customer support, research assistants | + +Hugging Face's pipeline API covers all of these tasks, including image segmentation, automatic speech recognition, and document question answering. Each maps cleanly to a Python web app because every task follows the same structure: a user-facing input component, a backend event handler that calls the model, and an output component that updates when state changes. + +## Connecting Hugging Face to Your Reflex App + +Reflex's backend runs standard Python, which means any library you can pip install works inside your app. Hugging Face is no exception. Because all model calls live inside Reflex state event handlers, your ML logic sits right alongside your UI state, with no separate API server required. + +### Authentication and Setup + +Start by grabbing a Hugging Face API token from your account settings, then store it as an environment variable. Reflex picks this up at runtime like any Python app would. If you're working across multiple apps in a team environment, Reflex's project-level integration configuration lets you set credentials once and share them across every app in that project instead of reconfiguring each one separately. + +After installing Reflex and the Hugging Face libraries you need, your token is available to any event handler in your state class without additional wiring. + +### Model Loading Approaches + +You have two options here, and the right choice depends on your use case: + +- Hugging Face Inference API: The `InferenceClient` class gives you a simple interface to run any model hosted on Hugging Face without downloading weights locally. It supports most common tasks out of the box and is the fastest way to prototype, making it well-suited for serverless deployments where you want to offload compute. + +- Local model loading with Transformers: Load models directly into your Python environment using `pipeline()` from the Transformers library. This works better for latency-sensitive apps, private deployments, or when you need fine-tuned models that are not hosted publicly. + +For most production web apps, the Inference API is the cleaner starting point, though [background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) can optimize long-running model calls. You avoid managing GPU infrastructure, and the API surface stays consistent across every Hugging Face model task. Once your event handler gets a response back, Reflex updates UI state automatically, triggering a re-render without any extra code on your part. + +## Building the UI Around Hugging Face in Pure Python + +Reflex's component library, along with [custom components](https://reflex.dev/blog/custom-components/), gives you everything needed to build a production-grade UI around Hugging Face inference without writing a single line of JavaScript. A Python developer who knows their models can own the full stack: state, events, and UI all live in the same file, and you can jumpstart development with existing [Reflex templates](https://reflex.dev/templates/). + +Here is how each layer of the UI fits together: + +### Input Collection Components + +Input fields, text areas, file uploaders, and dropdowns all map directly to Reflex components. You bind each input to a state variable, which means the value is always available to your event handlers the moment a user interacts with the form. No serialization, no fetch calls, no form libraries needed. + +### Real-Time Result Display + +For text generation, Hugging Face responses can arrive progressively. Reflex's WebSocket-based state sync pushes each token or chunk to the browser as it arrives, so the UI updates in real time without polling. As [KDNuggets notes](https://www.kdnuggets.com/the-complete-hugging-face-primer-for-2026), you can run models directly via the API without expensive hardware, which pairs well with streaming output: results load fast even when the model is remote. + +### Error Handling and Loading States + +Your event handlers control a loading boolean in state. Set it to true before the inference call, false after. The UI reacts immediately, showing a spinner during inference and swapping in the result when it arrives. Errors get caught in the same handler and written to a state variable that surfaces a message in the UI, a pattern that works equally well in enterprise production environments. + +## Deploying Your Hugging Face App to Production + +When your app works locally, shipping it takes one command: `reflex deploy`. [Reflex Cloud](https://reflex.dev/hosting/) handles infrastructure provisioning, multi-region scaling, and SSL automatically. + +### Secrets Management for API Keys + +Never hardcode your Hugging Face token, a best practice followed by all serious [AI app builders](https://reflex.dev/blog/top-5-ai-app-builders/). Store it as an environment variable in Reflex Cloud, then reference it through your app's configuration layer. Your event handlers read it at runtime with no exposure in source control. + +### Performance Optimization at Scale + +A few things matter once you move beyond local development: + +- Cache repeated inference results for identical inputs, since model calls are expensive and often return the same output for common queries. + +- Set rate limits on your event handlers to avoid hammering the Hugging Face API during traffic spikes, which can cause timeouts or unexpected billing. + +- For latency-sensitive workloads, [Hugging Face Dedicated Inference Endpoints](https://endpoints.huggingface.co/) let you deploy with vLLM, TGI, SGLang, or custom containers instead of sharing public infrastructure. + +When Hugging Face handles sensitive data such as healthcare records, financial documents, or private user content, the public Inference API may not meet your compliance requirements, which is where [self-hosting with Docker](https://reflex.dev/blog/self-hosting-reflex-with-docker/) becomes necessary. For those cases, Reflex supports [VPC and on-premises deployment](https://reflex.dev/blog/on-premises-deployment/), keeping model calls inside your security perimeter entirely. + +## FAQ + +### Can I build a Hugging Face web app without learning JavaScript? + +Yes. Reflex lets you build the entire web app, frontend and backend, in pure Python. Your UI components, state management, and Hugging Face model calls all live in the same Python codebase, with no JavaScript required. + +### What's the difference between using Hugging Face Inference API vs loading models locally in a Python web app? + +The Inference API runs models on Hugging Face's infrastructure, making it faster to prototype and better for serverless deployments. Local loading with Transformers gives you lower latency and works better for private deployments or fine-tuned models, but requires managing your own compute resources. + +### How do I handle real-time streaming from Hugging Face text generation models in a web interface? + +Reflex's WebSocket-based state sync pushes each token to the browser as it arrives from Hugging Face, updating the UI in real time without polling. You write a standard Python event handler that yields results progressively, and the frontend updates automatically with each chunk. + +### When should I self-host my Hugging Face web app instead of using cloud deployment? + +Self-host when your Hugging Face models process sensitive data like healthcare records, financial documents, or private user content that can't leave your security perimeter. Reflex supports VPC and on-premises deployment, keeping model calls inside your compliance boundaries while maintaining the same Python codebase. diff --git a/blog/build-python-web-app-mssql.md b/blog/build-python-web-app-mssql.md new file mode 100644 index 000000000..36c6a672a --- /dev/null +++ b/blog/build-python-web-app-mssql.md @@ -0,0 +1,141 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With MSSQL in 2026" +title_tag: "Python Web App With MSSQL Guide 2026" +description: "Learn how to build Python web apps with MSSQL in April 2026. Complete tutorial covering database connections, UI components, and production deployment." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "MSSQL Python app, SQL Server web app, MSSQL integration Python, SQL Server Python app, enterprise database app" + } +] +faq: [ + {"question": "Can I build a Python web app with MSSQL without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire application—frontend UI, backend logic, and MSSQL queries—in pure Python. You write your database connections, state management, and interface components all in one language without touching JavaScript frameworks or separate frontend codebases."}, + {"question": "What's the fastest way to connect MSSQL to a Python web interface in 2026?", "answer": "Install Reflex, `pyodbc`, and the Microsoft ODBC Driver 18 for SQL Server, then create a connection string in your `.env` file. Write your queries inside Reflex event handlers, push results to state vars, and the UI updates automatically over WebSockets—no REST endpoints or manual DOM manipulation required."}, + {"question": "Reflex vs Streamlit for MSSQL dashboards?", "answer": "Streamlit reruns your entire script on every interaction, causing memory leaks and slowdowns with database queries. Reflex uses event-based state updates where only changed components re-render, and supports server push for real-time data updates without polling—critical for live financial reporting or operational dashboards reading from MSSQL."}, + {"question": "How do I deploy a Python MSSQL app to production?", "answer": "Run `reflex deploy` for managed cloud hosting with automatic HTTPS and multi-region availability. For compliance-sensitive workloads, use hybrid deployment (frontend on Reflex Cloud, backend and MSSQL in your network) or full on-premises deployment with Helm charts for Kubernetes environments—common in finance and healthcare."}, + {"question": "When should I use parameterized queries with MSSQL in Reflex?", "answer": "Always. Pass user inputs as bound parameters through `pyodbc`'s execute method rather than string interpolation to prevent SQL injection attacks. This is non-negotiable for any production application, especially in financial services or healthcare where data integrity and security audits are mandatory."}, + {"question": "Does Reflex support Windows Authentication for MSSQL connections?", "answer": "Yes, Reflex supports Windows Authentication through the connection string by setting `Trusted_Connection=yes` instead of using `UID` and `PWD` parameters. This is configured in your `.env` file and loaded at startup through the project-level integration that automatically shares across all apps."}, + {"question": "What ODBC driver version should I use with MSSQL and Reflex?", "answer": "Microsoft recommends ODBC Driver 18 for SQL Server for most current deployments. On macOS and Linux, you'll need to install this driver separately before `pyodbc` can connect, while Windows typically includes it by default."}, + {"question": "How does Reflex handle real-time updates from MSSQL databases?", "answer": "Reflex uses WebSocket-based server push to sync state changes to the browser automatically. When an event handler updates MSSQL data and pushes results to state vars, only the components tied to those changed state vars re-render without requiring full page reloads or manual polling."}, + {"question": "Can I use connection pooling with MSSQL in Reflex?", "answer": "Yes. Start simple by opening a connection per event handler call and closing it when done. If you encounter latency issues at scale, you can implement `pyodbc`'s built-in pooling or add a dedicated pool manager layer in your state class without changing your overall Reflex structure."}, + {"question": "Where should I store MSSQL credentials in a Reflex project?", "answer": "Store credentials in a `.env` file and load them at startup using `python-dotenv`. Never hardcode credentials in state classes. For production deployments, pass the connection string as an environment variable through the CLI, and the app reads it at runtime."}, + {"question": "What built-in monitoring does Reflex provide for MSSQL applications?", "answer": "Production Reflex apps include OpenTelemetry distributed tracing and ClickHouse log aggregation, giving you visibility into query latency, error rates, and state transition timelines. If an MSSQL query slows under load, you can see exactly where in the request cycle it happens without requiring a separate monitoring layer."}, + {"question": "How do I show loading states while waiting for MSSQL queries to complete?", "answer": "Use `yield` statements inside your event handlers to push a loading state to the browser before the query results arrive. This lets you update the UI mid-handler, providing user feedback during longer-running database operations."}, + {"question": "Can Reflex handle ACID-compliant financial workloads with MSSQL?", "answer": "Yes. MSSQL's ACID compliance for financial workloads is preserved in Reflex applications. You write parameterized queries inside event handlers that execute against your MSSQL database, maintaining the same transactional guarantees and security requirements needed for financial services and regulatory compliance."}, + {"question": "What components does Reflex provide for displaying MSSQL query results?", "answer": "Reflex ships with 60+ built-in components including `rx.data_table()` for displaying query results, `rx.recharts.line_chart()` for trend visualization, `rx.input()` and `rx.select()` for filtering, and AG Grid for advanced data grids. All components are written in Python without requiring JavaScript configuration."}, + {"question": "How does project-level MSSQL integration work in Reflex?", "answer": "Integrations in Reflex are configured once at the project level and automatically shared across every application within that project. You set your MSSQL connection configuration a single time, and every app in the project can reference it without duplicate configuration or scattered credential files."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Build full-stack web apps with MSSQL entirely in Python, with no JavaScript required for frontend or backend + +- Reflex connects to MSSQL via pyodbc with project-level integration sharing across all apps + +- Deploy with `reflex deploy` for managed hosting or use hybrid/on-prem options for compliance needs + +- Reflex is an open-source Python framework that lets you build production web apps connected to MSSQL databases + +## Why Python Developers Are Building Web Apps With MSSQL in 2026 + +Microsoft SQL Server has stayed at the center of enterprise infrastructure for decades, and 2026 is no different. It powers ERP and CRM systems, supports ACID-compliant financial workloads, and handles the secure data operations that healthcare and government organizations depend on. When your data lives in MSSQL, it's usually there for a reason: auditing, regulatory compliance, deep Microsoft ecosystem integration, or all three at once. + +The problem most Python teams run into is not the database itself. It's everything that comes after. You write clean Python for your data logic, your models, your business rules. Then someone asks for a web interface, and suddenly you're context-switching into JavaScript, managing two separate codebases, and watching your data scientists hit a wall they never should have hit. + +That split stack is where projects slow down. Frontend and backend drift apart, and the people who understand the data are no longer the people shipping the UI. + +Reflex removes that wall entirely. You write your MSSQL queries, your state logic, and your UI components all in Python with a [Python web application tutorial](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) approach. No JavaScript, no separate frontend repo. + +## What You'll Build: A Python Web App Powered by MSSQL + +To ground this in something real, picture a [Python admin panel](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) reading directly from MSSQL tables: transaction records, department budgets, and expense categories. Users filter by date range, drill into line items, and flag entries for review without ever leaving the browser. No Excel exports, no waiting on a data team. Just a live interface sitting on top of your existing database. + +Here's what that app actually includes: + +- A [filterable data table](https://reflex.dev/blog/using-table-component/) pulling live records from MSSQL + +- Dropdown filters for date range, department, and status + +- An editable row view for updating records and writing back to the database + +- A summary panel with running totals and variance indicators, similar to a [Reflex dashboard](https://reflex.dev/templates/finance-dashboard/) + +- Role-based access so finance managers see different views than analysts + +The component library ships 60+ built-in components out of the box, so you are not wiring up a React table or fighting a charting library. You pick the component, pass it your state, and move on. + +The backend compiles to FastAPI and syncs state to the browser over WebSockets through [Reflex architecture](https://reflex.dev/blog/reflex-architecture/). When a user updates a filter, the table refreshes in real time without a full page reload. It behaves like a production app because it is one. + +## Connecting MSSQL to Your Reflex App + +Getting MSSQL connected is where most tutorials skip the details that actually matter. Here is what you need to know to get it right. + +### Installing Required Dependencies + +You'll need three things installed before writing a single line of app code: Reflex itself, a Python ODBC driver for SQL Server, and a way to manage credentials without hardcoding them. The ODBC driver piece trips people up most often. On macOS and Linux, you'll need to [install the Microsoft ODBC Driver](https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server) for SQL Server separately before `pyodbc` can talk to your database. On Windows, it's usually already present, but worth confirming. The driver version matters too - Microsoft recommends ODBC Driver 18 for SQL Server for most current deployments. + +| Library | Purpose | Installation Command | +|---|---|---| +| reflex | Full-stack Python web framework | `pip install reflex` | +| pyodbc | ODBC database connectivity | `pip install pyodbc` | +| python-dotenv | Environment variable management | `pip install python-dotenv` | + +### Configuring the Database Connection + +Once your drivers are in place, the connection string follows a predictable format: `DRIVER`, `SERVER`, `DATABASE`, and either `UID`/`PWD` for SQL Server Authentication or `Trusted_Connection=yes` for Windows Authentication. Store everything in a `.env` file and load it at startup. Never put credentials directly in your state classes. + +In Reflex, integrations are configured at the project level and automatically shared across every application within that project. Set your MSSQL connection once, and every app in the project can reference it without duplicate configuration or scattered credential files. + +Your Reflex state class holds a method that opens a `pyodbc` connection using those environment variables. Event handlers call that method, execute queries, and push results into state vars. The UI reacts automatically. For connection pooling, keep it simple at first: open a connection per event handler call and close it when done. If you hit latency issues at scale, `pyodbc`'s built-in pooling or a dedicated pool manager layer in your state class will handle it without changing your overall Reflex structure. + +## Building the UI Around MSSQL in Pure Python + +Every database interaction in a Reflex app lives inside an event handler. To query MSSQL, you create a cursor from your connection and call its execute method with a parameterized query. Parameterization is non-negotiable: it [prevents SQL injection](https://realpython.com/prevent-python-sql-injection/) by passing user inputs as bound parameters instead of string-interpolated values. + +### Displaying Results with Data Components + +When a query might take a moment, `yield` statements let you push a loading state to the browser mid-handler before results arrive. Because Reflex uses WebSocket-based server push, only the components tied to changed state vars re-render. Everything else stays put. + +Once your event handler pushes results into state, the UI responds automatically. No manual DOM updates, no JavaScript callbacks. The Python developer who wrote the SQL owns the entire experience, front to back. + +Reflex provides built-in components like `rx.data_table()` for displaying query results, `rx.recharts.line_chart()` for visualizing trends, `rx.input()` and `rx.select()` for filtering data, and `rx.button()` for triggering queries. These components, including [AG Grid](https://reflex.dev/blog/using-ag-grid-in-reflex/), cover the most common patterns you will reach for when building data-driven apps: tabular results, trend visualization, and user-driven filtering. No JavaScript required at any point in that flow. + +## Deploying Your MSSQL App to Production + +When your app is ready, run `reflex deploy` and [Reflex Cloud](https://reflex.dev/hosting/) handles infrastructure provisioning, multi-region availability, and HTTPS automatically. Your MSSQL connection string stays out of the codebase entirely - pass it as an environment variable through the CLI at deploy time, and the app reads it at runtime. + +For enterprises with strict data residency or compliance requirements, two paths exist. A hybrid architecture lets you deploy the frontend to Reflex Cloud while keeping your backend and MSSQL instance inside your own network perimeter. For maximum control, [full on-premises deployment](https://reflex.dev/blog/on-premises-deployment/) runs the entire stack in your environment, which is common for financial services and healthcare organizations subject to SOC 2, HIPAA, or similar frameworks. + +Once deployed, production observability comes built in. OpenTelemetry distributed tracing and ClickHouse log aggregation give you query latency visibility, error rates, and state transition timelines without requiring a separate monitoring layer. If a MSSQL query slows under load, you see exactly where in the request cycle it happens. + +## FAQ + +### Can I build a Python web app with MSSQL without learning JavaScript? + +Yes. Reflex lets you build the entire application - frontend UI, backend logic, and MSSQL queries - in pure Python. You write your database connections, state management, and interface components all in one language without touching JavaScript frameworks or separate frontend codebases. + +### What's the fastest way to connect MSSQL to a Python web interface in 2026? + +Install Reflex, `pyodbc`, and the Microsoft ODBC Driver 18 for SQL Server, then create a connection string in your `.env` file. Write your queries inside Reflex event handlers, push results to state vars, and the UI updates automatically over WebSockets. No REST endpoints or manual DOM manipulation required. + +### Reflex vs Streamlit for MSSQL dashboards? + +Streamlit reruns your entire script on every interaction, causing memory leaks and slowdowns with database queries. Reflex uses event-based state updates where only changed components re-render, and supports server push for real-time data updates without polling. This is critical for live financial reporting or live dashboards reading from MSSQL. + +### How do I deploy a Python MSSQL app to production? + +Run `reflex deploy` for managed cloud hosting with automatic HTTPS and multi-region availability. For compliance-sensitive workloads, use hybrid deployment (frontend on Reflex Cloud, backend and MSSQL in your network) or full on-premises deployment with Helm charts for Kubernetes environments. This approach is common in finance and healthcare. + +### When should I use parameterized queries with MSSQL in Reflex? + +Always. Pass user inputs as bound parameters through `pyodbc`'s execute method instead of string interpolation to prevent SQL injection attacks. This is non-negotiable for any production application, especially in financial services or healthcare where data integrity and security audits are mandatory. diff --git a/blog/build-python-web-app-okta-auth.md b/blog/build-python-web-app-okta-auth.md new file mode 100644 index 000000000..0e75733d8 --- /dev/null +++ b/blog/build-python-web-app-okta-auth.md @@ -0,0 +1,153 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Okta Auth in 2026" +title_tag: "Python Web App With Okta Auth April 2026" +description: "Learn to build Python web apps with Okta authentication in April 2026. Complete OAuth flows, protected routes, and RBAC in pure Python without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Okta Python app, Okta auth web app, SSO Python app, Okta integration, enterprise login Python, identity management app" + } +] +faq: [ + {"question": "Can I build a Python web app with Okta auth without JavaScript?", "answer": "Yes. Reflex lets you build the complete Okta authentication flow in pure Python, including OAuth redirects, callback handling, session management, and protected routes. The full stack runs in Python, so you never need JavaScript to wire up enterprise auth."}, + {"question": "Okta auth with Reflex vs building with React and Flask?", "answer": "Reflex keeps the auth flow in a single Python codebase, while React + Flask splits session state between frontend JavaScript and backend Python. With Reflex, your Okta SDK calls, token validation, and protected route logic all live in the same State class that drives your UI, cutting the complexity in half."}, + {"question": "How do I handle role-based access control with Okta in Reflex?", "answer": "Read group membership claims from the Okta ID token and store them in your State class as variables like `user_role` or `user_groups`. Then check those variables in your components to show or hide sections, or in protected route handlers to restrict access before rendering pages."}, + {"question": "What's the deployment process for a production Okta auth app?", "answer": "Run `reflex deploy` and your app goes live with Okta credentials stored in Reflex Cloud secrets. For regulated industries, VPC deployment keeps auth traffic within your network perimeter, while on-premises deployment supports air-gapped environments with internal identity providers."}, + {"question": "When should I use the Okta SDK directly instead of the native integration?", "answer": "Use the native integration for standard OAuth flows with SSO and session management. Call the Okta Python SDK directly from event handlers when you need custom logic like advanced token validation, programmatic user provisioning, or non-standard authorization flows that go beyond basic authentication."}, + {"question": "Does Reflex support multi-factor authentication (MFA) with Okta?", "answer": "Yes. Okta handles MFA, passkey support, and device assurance policies as part of its authentication flow. When users authenticate through Okta in your Reflex app, they go through whatever MFA requirements are configured in your Okta organization."}, + {"question": "How does session management work with Okta in Reflex apps?", "answer": "Sessions persist automatically across page navigation in Reflex using state variables that store Okta tokens and user claims. Once authenticated, the session data lives in your Python State class, and users don't need to re-authenticate when navigating between protected routes."}, + {"question": "Can I use Okta with internal tools and admin panels built in Reflex?", "answer": "Yes. The Okta integration maps cleanly onto internal tools and admin panels that require enterprise authentication. You can build protected dashboards with role-based content that reads group membership directly from Okta claims stored in your State class."}, + {"question": "Where do I store Okta credentials in a Reflex project?", "answer": "Store Okta credentials in environment variables or Reflex Cloud secrets. Reflex configures integrations at the project level, so you set credentials once and every app in the project inherits them automatically without needing per-app reconfiguration."}, + {"question": "What happens to unauthenticated users on protected routes?", "answer": "Protected routes check the `is_authenticated` state variable before rendering. If the check fails, the event handler automatically redirects unauthenticated users to the login page without requiring manual redirect logic."}, + {"question": "Can I integrate Okta with existing Python backends or do I need to rebuild?", "answer": "You can integrate any Python SDK directly into Reflex event handlers, so existing Python code that calls the Okta SDK works without modification. The full authentication flow, from OAuth to session management, runs in the same Python State class that drives your UI."}, + {"question": "How does Reflex handle OAuth callback URLs from Okta?", "answer": "Your Reflex app registers a callback URL that Okta redirects to after authentication. The callback page's event handler receives the authorization code, exchanges it for tokens using the Okta SDK, and writes the resulting claims into state variables like `user_email` and `user_groups`."}, + {"question": "Does Reflex support air-gapped or on-premises Okta deployments?", "answer": "Yes. Reflex supports on-premises deployment for air-gapped environments where Okta connects to internal identity providers without external exposure. This meets compliance requirements for regulated industries that cannot use public cloud infrastructure."}, + {"question": "How do I restrict which team members can modify Okta configuration?", "answer": "Use RBAC in your deployment environment to restrict which team members can modify authentication configuration. This reduces the attack surface from insider risk, particularly important in regulated industries with strict access controls."}, + {"question": "Can Reflex integrate with Okta's device assurance policies?", "answer": "Yes. Okta's device assurance policies update dynamically with OS versions and are enforced during the authentication flow. When users authenticate through Okta in your Reflex app, they're subject to whatever device assurance policies are configured in your Okta organization."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build production web apps with Okta authentication entirely in Python using Reflex + +- OAuth flows, protected routes, and RBAC all live in Python state classes without JavaScript + +- Reflex handles Okta credentials at the project level and deploys with `reflex deploy` + +- VPC and on-premises deployment options meet enterprise compliance requirements + +- Reflex is a Python framework that lets you build full-stack web apps without learning React + +## Why Python Developers Are Building Web Apps With Okta Auth in 2026 + +Enterprise authentication has gotten harder to ignore. More teams are shipping internal tools with SSO requirements, MFA mandates, and user lifecycle policies baked in from day one. Okta has become the identity standard for most of those organizations, handling the full stack of enterprise auth: single sign-on, multi-factor authentication, passkey support, and device assurance policies that now update dynamically with OS versions instead of requiring manual updates. + +The problem for Python developers is usually not Okta itself. It's everything around it. OAuth callback handling, redirect chains, frontend session state, protected route logic: all of it typically lives in JavaScript. So Python developers end up bolting a React layer onto a Python backend just to handle auth, which creates two codebases, two mental models, and a longer path to production. + +Reflex changes that equation entirely. Because the full stack runs in Python, you write your Okta integration once as a Python event handler, and the auth flow, session management, and protected routes all live in the same codebase. + +Okta Auth is a supported integration in Reflex, with project-level configuration that sets credentials once and shares them across every app in the project. Any Python SDK can be called directly from a Reflex event handler, so you never need to leave Python to own the complete authentication flow. + +## What You'll Build: A Python Web App Powered by Okta Auth + +The app you're building is a protected dashboard that handles the full Okta authentication lifecycle without a single line of JavaScript. + +Here's the flow from the user's perspective: + +- User lands on the app and clicks "Sign in with Okta," triggering the OAuth redirect to your Okta-hosted login page (similar to [implementing Sign In with Google](https://reflex.dev/blog/implementing-sign-in-with-google/)). + +- After authenticating, Okta sends them back via an OAuth callback URL your app registers. + +- The app validates the token, creates a session, and reads group membership claims from the Okta response. + +- The user lands on a role-specific dashboard showing only the content they are authorized to see. + +That last step is where role-based access control (RBAC) comes in. A user in the `admin` Okta group sees a management panel. A user in the `viewer` group sees read-only dashboards. No role means no access. All of this lives in Reflex's Python-based state management, where a single state class tracks authentication status, session tokens, and user metadata returned from Okta. + +Protected routes follow the same pattern. Each page checks state before it displays, and unauthenticated users get redirected automatically. Sessions persist across page navigation without forcing a re-authentication loop. + +This architecture maps cleanly onto [internal tools and admin panels](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) and data dashboards that require enterprise auth. The Okta integration owns identity; Reflex owns everything else in pure Python. + +## Connecting Okta Auth to Your Reflex App + +The wiring pattern for Okta in Reflex follows a straightforward structure: credentials live in environment variables or Reflex Cloud secrets, a backend State class owns the OAuth flow, and auth state flows directly into your UI components. No middleware layer, no separate auth service, no JavaScript callbacks. This approach aligns with [enterprise SSO best practices](https://www.reco.ai/learn/sso-best-practices) for secure authentication protocols. + +| Configuration Element | Purpose | Storage Location | +|---|---|---| +| Okta Domain | Your Okta organization URL | Environment variable or Reflex Cloud secrets | +| Client ID | OAuth application identifier | Environment variable or Reflex Cloud secrets | +| Client Secret | OAuth application credential | Environment variable or Reflex Cloud secrets | +| Redirect URI | Callback URL after Okta authentication | Reflex app configuration | + +Because Reflex configures integrations at the project level (just like with [Microsoft Azure Auth](https://reflex.dev/blog/microsoft-azure-authentication/)), you set these credentials once and every app in the project inherits them automatically. No per-app reconfiguration, no drift between environments. + +> + +The Okta SDK supports OAuth 2.0 for service-to-service applications, with access tokens controlling which actions can be performed on specific Okta endpoints through scopes. ([github.com/okta/okta-sdk-python](https://github.com/okta/okta-sdk-python)) + +Your State class handles three responsibilities: initiating the OAuth redirect, processing the callback token, and storing session data like user claims and group membership. The Okta Python SDK gets imported directly into your event handlers, since any PyPI package works this way in Reflex. Token verification, claim extraction, and session writes all happen in the same Python class that drives your UI. Reflex Cloud secrets management keeps credentials out of your codebase while VPC deployment options satisfy [stricter enterprise security requirements](https://reflex.dev/blog/enterprise-ready-ai-app-builder/). For teams needing custom logic beyond the native Okta integration, calling the SDK directly from any event handler gives you full control over the authentication flow without leaving Python. + +## Building the UI Around Okta Auth in Pure Python + +Every UI element in a Reflex app reads directly from state variables, which means your Okta session data flows into components the same way any Python variable would. When authentication state changes, the UI updates automatically without any manual DOM updates or client-side JavaScript. + +| UI Component | Okta Auth Function | State Variable | +|---|---|---| +| Login button | Initiates OAuth redirect to Okta | `auth_url` | +| Callback handler | Processes authorization code and fetches tokens | `access_token`, `id_token` | +| Protected route | Validates session and checks user permissions | `is_authenticated`, `user_role` | +| User profile display | Shows claims from Okta ID token | `user_email`, `user_name`, `user_groups` | + +The login button is a Reflex component wired to an event handler that triggers the OAuth redirect. Clicking it calls a Python function, which builds the Okta authorization URL and updates state. The redirect happens server-side, with no JavaScript glue required. + +After Okta sends the user back, the callback page's event handler receives the authorization code, calls the Okta SDK to exchange it for tokens, and writes the resulting claims into state variables like `user_email` and `user_groups`. From that point, any component in your app can read those variables directly. + +Protected routes check `is_authenticated` before they display. If the check fails, the event handler redirects to the login page. Role-based display works the same way: a conditional in your component reads `user_role` from state and shows or hides sections accordingly. Developers who know the Okta Python SDK can build all of this without touching React or managing separate frontend session logic. + +## Deploying Your Okta Auth App to Production + +Deployment is one command: `reflex deploy`. Okta credentials stay in Reflex Cloud secrets, never committed to git, and automatically injected at runtime. Your production redirect URIs update to HTTPS, session persistence works across multi-region deployments, and built-in monitoring surfaces authentication failures before users report them. SSL certificates, session storage, and health checks are handled automatically by [Reflex Cloud's infrastructure](https://reflex.dev/hosting/). + +For finance, healthcare, and government sectors, compliance requirements shape how you deploy: + +- VPC deployment keeps authentication traffic within your network perimeter, so sensitive identity data never transits public infrastructure. + +- [On-premises deployment](https://reflex.dev/blog/on-premises-deployment/) supports air-gapped environments where Okta connects to internal identity providers without external exposure. + +- RBAC restricts which team members can modify authentication configuration, reducing the attack surface from insider risk. + +- Helm chart orchestration integrates with existing Kubernetes and GitOps pipelines for environments with strict infrastructure requirements. + +[Finance](https://reflex.dev/use-cases/finance/), healthcare, and government teams running Okta with Reflex consistently land here because the security model does not require compromises. The deploy quick-start guide covers cloud deployment, while [self-hosting docs](https://reflex.dev/blog/self-hosting-reflex-with-docker/) walk through on-premises configuration for enterprise environments. + +## FAQ + +### Can I build a Python web app with Okta auth without JavaScript? + +Yes. Reflex lets you build the complete Okta authentication flow in pure Python, including OAuth redirects, callback handling, session management, and protected routes. The full stack runs in Python, so you never need JavaScript to wire up enterprise auth. + +### Okta auth with Reflex vs building with React and Flask? + +Reflex keeps the auth flow in a single Python codebase, while React + Flask splits session state between frontend JavaScript and backend Python. With Reflex, your Okta SDK calls, token validation, and protected route logic all live in the same State class that drives your UI, cutting the complexity in half. + +### How do I handle role-based access control with Okta in Reflex? + +Read group membership claims from the Okta ID token and store them in your State class as variables like `user_role` or `user_groups`. Then check those variables in your components to show or hide sections, or in protected route handlers to restrict access before pages display. + +### What's the deployment process for a production Okta auth app? + +Run `reflex deploy` and your app goes live with Okta credentials stored in Reflex Cloud secrets. For compliance-heavy industries, VPC deployment keeps auth traffic within your network perimeter, while on-premises deployment supports air-gapped environments with internal identity providers. + +### When should I use the Okta SDK directly instead of the native integration? + +Use the native integration for standard OAuth flows with SSO and session management. Call the Okta Python SDK directly from event handlers when you need custom logic like advanced token validation, programmatic user provisioning, or non-standard authorization flows that go beyond basic authentication. diff --git a/blog/build-python-web-app-ollama.md b/blog/build-python-web-app-ollama.md new file mode 100644 index 000000000..fa52d26f7 --- /dev/null +++ b/blog/build-python-web-app-ollama.md @@ -0,0 +1,152 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Ollama in 2026" +title_tag: "Build Python Web App With Ollama 2026" +description: "Learn to build a Python web app with Ollama in April 2026. Get streaming responses, model selection, and real auth using Reflex—no JavaScript needed." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Ollama Python app, Ollama web app, local LLM Python app, self-hosted AI app, Ollama integration, private LLM app" + } +] +faq: [ + {"question": "Can I build a web app with Ollama without learning JavaScript?", "answer": "Yes. Reflex is a full-stack Python framework that handles both frontend and backend, so you can build a complete Ollama-powered web app using only Python. You get production-ready UI components, real-time streaming, and state management without touching React or Next.js."}, + {"question": "What's the best framework for building an Ollama chat interface in Python?", "answer": "Reflex gives you the cleanest path from Ollama integration to production web app. Unlike Streamlit (which has memory leaks and no real state management) or building custom React frontends, Reflex provides 60+ UI components, WebSocket-based streaming, and single-command deployment—all in pure Python."}, + {"question": "How does Reflex handle streaming responses from Ollama?", "answer": "Reflex uses background tasks with yield statements to push token chunks to the browser as they arrive from Ollama. Each yield triggers an automatic state update over WebSocket, creating a live typing effect without polling or manual refresh logic. The streaming pattern works identically whether you're calling Ollama locally or a cloud API."}, + {"question": "Where should the Ollama model run when deploying to production?", "answer": "For regulated industries or offline workflows, self-host both Reflex and Ollama on the same server or within a private VPC. For teams wanting cloud convenience, Reflex supports hybrid deployments where the frontend lives on Reflex Cloud while connecting to your on-premises Ollama backend, keeping model inference entirely within your network."}, + {"question": "Why run Ollama locally instead of using a cloud LLM API?", "answer": "Local Ollama instances keep sensitive data on-premises (critical for healthcare and finance), eliminate per-token API costs, remove vendor dependency, and work offline. The tradeoff is hardware requirements, but multimodal models with 4-bit quantization run efficiently on consumer GPUs in 2026."}, + {"question": "How do I install and set up Ollama for use with Reflex?", "answer": "Install the Ollama Python SDK with `pip install ollama` and Reflex with `pip install reflex`. Make sure the Ollama server is running locally, then pull a model to use in your app. You can verify the setup by listing available models through the SDK."}, + {"question": "Does Reflex require any API keys or credentials to connect to Ollama?", "answer": "No. Since Ollama runs locally, there are no API keys or environment variables to configure. The Ollama SDK connects to localhost by default and handles the connection automatically, unlike cloud API integrations that require authentication tokens."}, + {"question": "What are the hardware requirements for running Ollama models locally?", "answer": "While specific requirements vary by model, Ollama in 2026 supports optimized 4-bit quantization that allows large models to run efficiently on consumer GPUs. Loaded models stay resident in GPU memory (VRAM), so monitor your VRAM usage and account for disk space per model file."}, + {"question": "Can I use multiple Ollama models in the same Reflex app?", "answer": "Yes. On app load, you can fetch all installed Ollama models and store them in a state variable. Users can select different models through a dropdown, and when they submit a prompt, the event handler passes the selected model directly into the Ollama API call."}, + {"question": "What UI components does Reflex provide for building chat interfaces?", "answer": "Reflex's component library includes 60+ pre-built UI elements like inputs, containers, buttons, and dropdowns—all defined in Python. For chat interfaces specifically, you can compose message containers, scrollable lists of chat bubbles, text input fields, and submit buttons using Python functions with built-in responsive styling."}, + {"question": "How does Reflex compare to Streamlit for building Ollama applications?", "answer": "Unlike Streamlit, which has memory leaks and no real state management, Reflex provides production-ready UI components, WebSocket-based streaming, proper state management, and single-command deployment—all while keeping everything in pure Python without requiring JavaScript knowledge."}, + {"question": "Is Ollama secure by default when deployed to production?", "answer": "No. Ollama ships with no built-in authentication and by default binds to localhost only. In production, you need to implement security at the application layer using Reflex's authentication integrations with services like Clerk, Okta, or Azure Auth, and configure firewall rules to restrict access to port 11434."}, + {"question": "What network considerations should I be aware of when running Ollama?", "answer": "By default, Ollama binds to localhost only for security. If you expose it on all network interfaces without a firewall, anyone on your local network can query your models. Keep Ollama on localhost or behind proper network controls, and use application-layer authentication in production."}, + {"question": "Can I deploy a Reflex app with Ollama to the cloud?", "answer": "Yes, using a hybrid deployment architecture. You can deploy the Reflex frontend to Reflex Cloud while keeping Ollama running on your on-premises backend. Point the cloud frontend at your internal backend URL, and all model inference stays entirely within your private network."}, + {"question": "How does Reflex handle real-time updates without polling the server?", "answer": "Reflex uses WebSocket connections to push state updates from the backend to the browser automatically. When your event handler yields after each token chunk from Ollama, Reflex sends that state delta over WebSocket, creating a live typing effect without any polling or manual refresh logic."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Ollama runs LLMs locally on your hardware, keeping data on-premises and eliminating per-token API costs + +- Reflex lets you build production chat UIs around Ollama in pure Python without touching JavaScript + +- You get streaming responses through WebSockets, model selection dropdowns, and real auth, all server-side + +- Reflex is an open-source Python framework that builds full-stack web apps, trusted by 40% of Fortune 500 companies + +## Why Python Developers Are Building Web Apps With Ollama in 2026 + +Local AI changed the calculus for Python developers this year. Ollama has become the de facto standard CLI tool for running local LLMs in 2026, driven by data privacy mandates, unpredictable API pricing, and growing need for offline-capable workflows. Instead of routing sensitive data through a cloud API, you run the model on your own hardware. No network calls. No per-token billing surprises. No vendor dependency. + +Under the hood, Ollama wraps llama.cpp inference behind a simple REST API, abstracting model quantization, GPU memory allocation, and model file management. That means a Python developer can pull a model and start querying it locally in minutes. Running LLMs locally with Ollama keeps sensitive information on-premises, reduces latency by eliminating remote server communication, and gives industries like healthcare and finance actual control over model configurations. + +The problem has always been the frontend. Python developers who want to wrap Ollama in a real web interface either learn React or settle for something that looks like a prototype forever. + +That's where Reflex fits. We built [a full-stack Python framework](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) so developers never have to touch JavaScript. You get a production-ready web app, real state management, and a clean UI around your Ollama integration--all in pure Python. No React, no Next.js, no context switching. + +## What You'll Build: A Python Web App Powered by Ollama + +By the end of this tutorial, you'll have a working [chat web app](https://reflex.dev/templates/chat-bot/) that talks to a locally-running Ollama instance. Here's what the finished app does: + +- Lets users select from any Ollama model installed on their machine + +- Accepts prompt input through a chat-style interface + +- Streams LLM responses back in real-time as tokens arrive + +- Updates the UI automatically via WebSocket, with no page refresh needed + +The interaction loop is straightforward. A user submits a prompt, Reflex's backend state calls the Ollama Python library with `stream=True`, and tokens flow back through a WebSocket connection as they're generated. The component library handles all the display logic, so you won't be wiring up any manual polling or frontend event listeners. + +What makes this setup worth building is the infrastructure story. Everything runs on your local machine. No external API keys, no per-token costs, no data leaving your environment. That matters for industries with compliance requirements, offline workflows, or any situation where you'd rather not send user input to a third-party server. + +### Why Local AI Changes the Equation + +Most chat app tutorials assume you're calling out to a hosted model like Claude Opus 4.6 or Gemini 3.1 Pro. Ollama flips that assumption. You get the same streaming response pattern, but the model runs entirely in your own process. The tradeoff is hardware requirements, but the privacy and cost benefits are real for the right use cases. + +## Connecting Ollama to Your Reflex App + +Getting Ollama talking to Reflex requires two installs and one command. First, install the Ollama Python SDK with `pip install ollama`, then install Reflex with `pip install reflex`. Before running anything, make sure the Ollama server is active locally. Once it's running, pull a model to use in the app. From there, you can verify the setup is working by listing available models through the SDK. + +One network note worth flagging: [by default, Ollama binds to localhost only](https://www.aitooldiscovery.com/how-to/run-ollama-locally). If you expose it on all interfaces without a firewall, anyone on your local network can query your models. Keep that in mind before changing any binding settings. + +### Wiring Ollama Into Reflex State + +Here's where Reflex's architecture pays off. Reflex state classes are plain Python classes, which means you import the Ollama SDK exactly like any other library. No wrappers, no adapters. Your event handlers call `ollama.chat()` or `ollama.generate()` directly, and the return values go straight into state variables. + +Unlike cloud API integrations, local Ollama instances require zero credentials. No API keys, no environment variables to configure. The SDK connects to `localhost` by default and handles the rest. + +For streaming responses, [Reflex background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) are the right tool. They let you yield partial state updates as tokens arrive, pushing each chunk to the UI through Reflex's WebSocket connection without blocking the event loop. The UI rerenders on each yield automatically, with no polling or manual refresh logic required. + +## Building the UI Around Ollama in Pure Python + +Reflex's [component library](https://reflex.dev/blog/custom-components/) gives you 60+ pre-built UI elements, including inputs, containers, buttons, and dropdowns, all defined in Python. No HTML templates, no JSX, no CSS-in-JS. The styling system handles responsive layouts through Python keyword arguments, so your chat interface adapts to different screen sizes without a separate stylesheet. + +### Creating the Chat Interface Components + +A chat UI in Reflex is a composition of Python functions. A message container wraps a scrollable list of chat bubbles, a text input field captures the prompt, and a submit button triggers the event handler. Each component accepts styling props directly, keeping layout logic co-located with structure. The result is a readable, single-file app that any Python developer can scan and understand without frontend knowledge. + +### Streaming Responses to the Frontend + +The streaming pattern is where Reflex's architecture earns its keep. Your event handler iterates over the Ollama streaming response, appending each token chunk to a state variable, then yields after each update. Reflex pushes that state delta to the browser over WebSocket automatically, producing a live typing effect with no JavaScript and no polling. [Ollama's 2026 multimodal and 4-bit quantization support](https://textify.ai/ollama-2026-guide-local-llm/), so large models run efficiently on consumer hardware and that stream arrives fast. + +### Handling Multiple Ollama Models + +Model selection lives entirely in state. On app load, an event handler calls the Ollama SDK to fetch installed models and stores the list in a state variable. A dropdown reads from that variable and updates a selected model on change. When the user submits a prompt, the event handler passes that selection directly into the Ollama API call, with no client-side logic anywhere. + +## Deploying Your Ollama App to Production + +Shipping your Ollama app to production requires one architectural decision upfront: where does the model run? [local LLMs have become core developer tools](https://www.sitepoint.com/run-local-llms-2026-complete-developer-guide/), but production deployment is still a different problem than local development. + +### Deploying to Reflex Cloud + +`reflex deploy` handles the Reflex app itself cleanly, but Ollama needs a running local service, which cloud deployments don't include by default. For teams who want a cloud frontend, Reflex supports hybrid deployment architectures where the frontend lives on [Reflex Cloud infrastructure](https://reflex.dev/hosting/) while the backend connects to services running in your own environment. Point the cloud frontend at your [on-premises backend](https://reflex.dev/blog/on-premises-deployment/) URL and Ollama stays entirely within your network. + +### Self-Hosting With Ollama + +For true local-first deployments, [self-hosting](https://reflex.dev/blog/self-hosting-reflex-with-docker/) keeps everything co-located. Run Ollama as a system service so it restarts automatically. Configure firewall rules to restrict which hosts can reach port 11434. Monitor VRAM usage as loaded models stay resident in GPU memory, and account for disk space per model file. + +### Security and Access Control + +Ollama ships with no built-in authentication. In production, you need to handle that at the application layer. Reflex's authentication integrations with [Clerk](https://reflex.dev/blog/implementing-sign-in-with-google/), Okta, or Azure Auth let you gate access before any prompt reaches the model. For industries with strict compliance requirements, running both Reflex and Ollama inside a private VPN means inference never touches an external network. + +| Deployment Target | Ollama Location | Best For | Configuration Notes | +|---|---|---|---| +| Local Development | localhost:11434 | Prototyping, Testing | Default setup, no auth required | +| Self-Hosted Server | Same server as Reflex | Internal tools, Team apps | Configure firewall, monitor resources | +| VPC Deployment | Private network endpoint | Enterprise, Compliance | Network isolation, application-layer auth | +| Hybrid Cloud | On-premises backend | Compliance-driven industries | Frontend on Reflex Cloud, backend on-prem | + +## FAQ + +### Can I build a web app with Ollama without learning JavaScript? + +Yes. Reflex is a full-stack Python framework that handles both frontend and backend, so you can build a complete Ollama-powered web app using only Python. You get production-ready UI components, real-time streaming, and state management without touching React or Next.js. + +### What's the best framework for building an Ollama chat interface in Python? + +Reflex gives you the cleanest path from Ollama integration to production web app. Unlike Streamlit (which has memory leaks and no real state management) or building custom React frontends, Reflex provides 60+ UI components, WebSocket-based streaming, and single-command deployment--all in pure Python. + +### How does Reflex handle streaming responses from Ollama? + +Reflex uses background tasks with yield statements to push token chunks to the browser as they arrive from Ollama. Each yield triggers an automatic state update over WebSocket, creating a live typing effect without polling or manual refresh logic. The streaming pattern works identically whether you're calling Ollama locally or a cloud API. + +### Where should the Ollama model run when deploying to production? + +For industries with compliance requirements or offline workflows, self-host both Reflex and Ollama on the same server or within a private VPC. For teams wanting cloud convenience, Reflex supports hybrid deployments where the frontend lives on Reflex Cloud while connecting to your on-premises Ollama backend, keeping model inference entirely within your network. + +### Why run Ollama locally instead of using a cloud LLM API? + +Local Ollama instances keep sensitive data on-premises (critical for healthcare and finance), eliminate per-token API costs, remove vendor dependency, and work offline. The tradeoff is hardware requirements, but multimodal models with 4-bit quantization run efficiently on consumer GPUs in 2026. diff --git a/blog/build-python-web-app-with-notion.md b/blog/build-python-web-app-with-notion.md new file mode 100644 index 000000000..c21fb188e --- /dev/null +++ b/blog/build-python-web-app-with-notion.md @@ -0,0 +1,159 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Notion in 2026" +title_tag: "Build Python Web App With Notion in 2026" +description: "Learn how to build a Python web app with Notion in April 2026. Connect to Notion's API, create interactive dashboards, and deploy production apps using pure Python." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Notion Python app, Notion API web app, Notion integration Python, productivity app Python, Notion database app" + } +] +faq: [ + {"question": "Can I build a Notion web app without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire frontend and backend in pure Python using the `notion-client` SDK. You write UI components like `rx.table` and `rx.form` in Python, wire them to Notion's API through state classes, and deploy without touching any `.jsx` files or React code."}, + {"question": "What's the best Python framework for building a Notion dashboard in 2026?", "answer": "Reflex is purpose-built for this use case—it gives you 60+ components that map directly to Notion's data structures, two-way API sync through WebSocket state updates, and production deployment with a single command. Streamlit can't handle server push for real-time updates, and Dash requires callback spaghetti for interactive forms."}, + {"question": "How do I authenticate my Python app with Notion's API?", "answer": "Create an internal integration in Notion's developer portal, grab the Integration Secret, and store it as an environment variable in your Reflex project. Initialize the `notion-client` with that token inside your state class, then explicitly share the databases or pages you want to access with your integration in Notion itself—integrations don't get automatic workspace access."}, + {"question": "When should I use Reflex Cloud versus self-hosting for Notion integrations?", "answer": "If your Notion workspace contains regulated data (healthcare records, financial documentation, government project tracking), use Reflex's VPC or on-premises deployment to keep data inside your security perimeter. For standard internal tools where latency and uptime matter more than data sovereignty, Reflex Cloud handles multi-region scaling and secrets management automatically."}, + {"question": "How long does it take to build a working Notion web app with Reflex?", "answer": "Most teams go from authentication setup to a functional dashboard in 2-3 hours. Query a database with `client.databases.query()`, assign results to a state variable, render them with `rx.table` or `rx.foreach`, and you're live. Adding create/update forms and real-time sync takes another hour or two depending on your data model."}, + {"question": "What Notion API operations do I need to build a full CRUD interface?", "answer": "You'll use four main operations: `client.databases.query()` to fetch records, `client.pages.retrieve()` to get individual page properties, `client.pages.create()` to add new entries, and `client.pages.update()` to modify existing properties. For adding rich content to pages, use `client.blocks.children.append()`."}, + {"question": "Can I build real-time Notion dashboards that update automatically without page refreshes?", "answer": "Yes. Reflex's WebSocket sync pushes state updates to the browser automatically whenever an event handler completes a Notion API call. When users modify data through your app, the UI reflects changes immediately without any manual refresh logic or polling."}, + {"question": "Do I need to give my Notion integration access to my entire workspace?", "answer": "No. Integrations don't get automatic access to anything in your workspace. You must explicitly share each database or page you want the integration to access by inviting it directly inside Notion—this gives you granular control over what your app can read and modify."}, + {"question": "How do I handle Notion's rich text fields in a Python web app?", "answer": "Notion's rich text fields return as arrays of text objects that you can parse and pass directly into Reflex components like `rx.text` or `rx.markdown`. The component library handles rendering without requiring any JavaScript transformation code."}, + {"question": "What's the best way to filter and search Notion database entries in my app?", "answer": "Use the `client.databases.query()` method with filter parameters to retrieve only the records you need from Notion's API. Assign the filtered results to a Reflex state variable, then render them with components like `rx.table` or `rx.foreach` for display."}, + {"question": "Can I monitor my Notion app's performance and API usage in production?", "answer": "Yes. Reflex includes built-in OpenTelemetry distributed tracing and ClickHouse log aggregation that let you monitor Notion API call patterns, track latency spikes, and set up alerts before issues affect users."}, + {"question": "How do I handle long-running Notion API queries without freezing my UI?", "answer": "Use Reflex's background tasks feature to execute long-running operations like querying large databases. Background tasks let you yield intermediate states so the interface stays responsive and users see progress updates throughout the operation."}, + {"question": "What happens if my Notion integration token gets exposed or compromised?", "answer": "Store your integration token as an environment variable in Reflex Cloud's dashboard where it stays encrypted at rest, never in your repository. If compromised, you can revoke the token in Notion's developer portal and generate a new one without redeploying your app—just update the environment variable."}, + {"question": "Can I build different views of the same Notion database for different user roles?", "answer": "Yes. Query the same Notion database with different filter parameters based on user context in your Reflex state class, then render role-specific views using conditional logic in your Python components. The filtering happens server-side before data reaches the browser."}, + {"question": "Do I need separate Notion integrations for development and production environments?", "answer": "It's recommended. Create separate internal integrations for development and production workspaces to prevent test data from mixing with live data. Configure each environment's integration token as a separate environment variable in your Reflex deployment settings."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build production web interfaces for Notion databases using pure Python - no JavaScript required. + +- Reflex connects directly to Notion's API through Python state classes, handling two-way data sync automatically. + +- Deploy with `reflex deploy` for instant production hosting, or use VPC/on-prem options for compliance needs. + +- Reflex is an open-source Python framework that lets you build full-stack web apps without frontend expertise. + +## Why Python Developers Are Building Web Apps With Notion in 2026 + +Notion has quietly become something more than a note-taking app for most Python development teams. It's where documentation lives, where project databases get built, where content gets organized across dozens of interconnected pages. The data is already there. The problem is getting it out in a way that's actually useful to stakeholders who don't want to use Notion themselves. + +Most developers solve this with a one-off script that hits the Notion API and dumps results into a CSV or Slack message. That works once. It doesn't work as a repeatable, interactive experience for a team. + +Traditional [Python web frameworks require JavaScript expertise](https://medium.com/the-pythonworld/12-modern-python-frameworks-to-try-in-2026-e7089305bb19) or sacrifice interactivity for simplicity. You either learn React to build proper UIs, or settle for static dashboards that can't handle real-time updates. + +Notion's REST API lets you create, update, and retrieve page content, manage databases, and interact with workspace properties directly. That's a legitimate backend for a web app. What's missing is a frontend layer that [Python developers can actually build](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) without learning JavaScript or React. + +Whether you're surfacing a Notion content calendar, building a project tracker, or exposing a database to non-technical users, the workflow is the same: write the UI in Python, wire it to Notion's API in Python, and deploy a production app without touching a single `.jsx` file. + +## What You'll Build: A Python Web App Powered by Notion + +The app you're building is a content management dashboard that sits on top of a Notion database. Your team gets a custom web interface to view, filter, create, and update records without ever opening Notion directly. + +Here's what the core interaction loop looks like: + +- Authenticate with the Notion API using an integration token to create a secure connection between your Python app and your workspace + +- Query one or more Notion databases and display the results as real-time tables or card grids that non-technical teammates can actually use + +- Let users create new pages or update existing properties through forms built entirely in Python, no frontend code required + +- Reflect changes immediately in both the app and the underlying Notion workspace so nothing falls out of sync + +That last point matters. The Notion API supports two-way data flow, which means your app can monitor databases for changes and sync updates back automatically. You're building a live interface, not a read-only export tool. + +> + +The most common internal tool request is simple: "Can we get a custom view of our Notion data without everyone needing a Notion seat?" This is exactly what a [Python admin panel](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) looks like. + +The same pattern scales to other use cases too. Page creation workflows, content publishing pipelines, team wikis with custom search, sprint trackers with filtered views. Check out our [templates](https://reflex.dev/templates/) for more examples. If the data lives in Notion, the interface can live in your app. + +## Connecting Notion to Your Reflex App + +Getting Notion talking to your Reflex app takes three steps: create an integration, store your credentials, and call the API from your state class. + +### Creating Your Notion Integration + +Head to Notion's developer portal and [create a new internal integration](https://developers.notion.com/guides/get-started/create-a-notion-integration) for your workspace. Once created, grab the Internal Integration Secret from the Configuration tab. That token is how every API request authenticates. + +One thing workspace owners often overlook: integrations don't automatically access everything. You have to explicitly grant each integration permission to specific pages or databases by sharing them with the integration directly inside Notion. No explicit permission, no API access. + +### Configuring Credentials in Reflex + +Store your integration token as an environment variable instead of hardcoding it. Reflex's project-level configuration lets you set credentials once and share them across every app in that project, which saves repeated setup when you're running multiple dashboards off the same Notion workspace. + +The `notion-client` Python SDK installs via pip and works inside Reflex event handlers without any modifications. Import it, initialize the client with your token, and you're ready. + +### Calling Notion API from State Classes + +Your Reflex state class is where the API calls live. Initialize the Notion client inside an event handler, call the relevant endpoint, and assign the response to a state variable. Reflex's reactive state pattern handles the rest: any state change automatically triggers a UI update without you writing any refresh logic. + +Here's a reference for the operations you'll use most: + +| Notion API Operation | Python SDK Method | Common Use Case | +|---|---|---| +| Query database | `client.databases.query()` | Fetch filtered entries | +| Retrieve page | `client.pages.retrieve()` | Get page properties | +| Create page | `client.pages.create()` | Add new database entry | +| Update page | `client.pages.update()` | Modify properties | +| Append blocks | `client.blocks.children.append()` | Add page content | + +## Building the UI Around Notion in Pure Python + +Reflex's 60+ [built-in components](https://reflex.dev/blog/custom-components/) map cleanly to Notion's data structures. Query results come back as structured JSON, which you assign to state variables as Python lists or dicts. From there, `rx.table`, `rx.card`, or `rx.foreach` displays each record directly. + +### Displaying Notion Database Content + +Notion's rich text fields return as arrays of text objects, which you can parse and pass into `rx.text` or `rx.markdown` components without any JavaScript involved. The component library handles layout, theming, and responsiveness out of the box. + +### Creating Interactive Forms for Notion Updates + +[Forms are just Python functions](https://reflex.dev/open-source/). Build an input, bind its value to a state variable, and wire the submit button to an event handler that calls `client.pages.create()` or `client.pages.update()`. Add validation logic inside the handler itself: check required fields, set an error state variable if something's missing, and the UI updates accordingly. Select menus for Notion's multi-select properties, date pickers for date fields, and text areas for rich content all follow the same pattern, with no frontend code or JavaScript callbacks required. + +### Real-Time State Updates + +When an event handler completes a Notion API call, Reflex's WebSocket sync pushes the updated state to the browser automatically. There's no refresh logic to write or loading states to manage manually. The UI responds the moment the handler returns. For longer operations like querying large databases, [background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) let you yield intermediate states so the interface stays responsive throughout. + +## Deploying Your Notion App to Production + +Once your app is ready, deployment is a single command. Run `reflex deploy` from your project directory and [Reflex Cloud](https://reflex.dev/hosting/) handles the rest, from infrastructure provisioning to multi-region availability for teams spread across time zones. The full deploy quick start walks through the process step by step. + +Secrets management is straightforward. Set your Notion integration token as an environment variable in the Reflex Cloud dashboard instead of hardcoding it. That credential stays encrypted at rest and never touches your repository. + +For teams in compliance-driven industries, Notion workspaces often hold documentation, project records, and business process data that carries compliance requirements. Reflex's self-hosting options include VPC deployment and [full on-premises support](https://reflex.dev/blog/on-premises-deployment/), giving security teams the data boundary controls they need. Hybrid architectures work here too: your frontend runs on Reflex Cloud's infrastructure while your backend connects to an internal Notion workspace behind your firewall. + +Production observability comes built in. OpenTelemetry distributed tracing and ClickHouse log aggregation let you monitor Notion API call patterns, catch latency spikes, and set alerts before users notice anything wrong. CI/CD integration with GitHub Actions or GitLab CI keeps your deployment pipeline clean as your app evolves. + +## FAQ + +### Can I build a Notion web app without learning JavaScript? + +Yes. Reflex lets you build the entire frontend and backend in pure Python using the `notion-client` SDK. You write UI components like `rx.table` and `rx.form` in Python, wire them to Notion's API through state classes, and deploy without touching any `.jsx` files or React code. + +### What's the best Python framework for building a Notion dashboard in 2026? + +Reflex is purpose-built for this use case - it gives you 60+ components that map directly to Notion's data structures, two-way API sync through WebSocket state updates, and production deployment with a single command. Streamlit can't handle server push for real-time updates, and Dash requires callback spaghetti for interactive forms. + +### How do I authenticate my Python app with Notion's API? + +Create an internal integration in Notion's developer portal, grab the Integration Secret, and store it as an environment variable in your Reflex project. Initialize the `notion-client` with that token inside your state class, then explicitly share the databases or pages you want to access with your integration in Notion itself - integrations don't get automatic workspace access. + +### When should I use Reflex Cloud versus self-hosting for Notion integrations? + +If your Notion workspace contains compliance-sensitive data (healthcare records, financial documentation, government project tracking), use Reflex's VPC or on-premises deployment to keep data inside your security perimeter. For standard internal tools where latency and uptime matter more than data sovereignty, Reflex Cloud handles multi-region scaling and secrets management automatically. + +### How long does it take to build a working Notion web app with Reflex? + +Most teams go from authentication setup to a functional dashboard in 2-3 hours. Query a database with `client.databases.query()`, assign results to a state variable, render them with `rx.table` or `rx.foreach`, and you're live. Adding create/update forms and real-time sync takes another hour or two depending on your data model. diff --git a/blog/build-python-web-app-with-stripe.md b/blog/build-python-web-app-with-stripe.md new file mode 100644 index 000000000..0957ad0c6 --- /dev/null +++ b/blog/build-python-web-app-with-stripe.md @@ -0,0 +1,144 @@ +--- +author: Tom Gotsman +date: 2026-04-07 +title: "How to Build a Python Web App With Stripe in 2026" +title_tag: "Build Python Web App With Stripe in 2026" +description: "Learn how to build a Python web app with Stripe integration in April 2026. Complete guide covering checkout sessions, webhooks, and deployment." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Stripe Python app, Stripe API web app, payment Python app, Stripe integration, billing app Python, Stripe checkout Python" + } +] +faq: [ + {"question": "Can I build a Stripe checkout flow without writing JavaScript?", "answer": "Yes. Full-stack Python frameworks like Reflex handle both frontend UI and backend payment logic in pure Python, so you never touch JavaScript while building production-ready checkout flows."}, + {"question": "Stripe Checkout vs Payment Intents for Python web apps?", "answer": "Stripe Checkout provides a hosted payment page that handles card input, fraud detection, and 3DS automatically, making it the simplest integration. Payment Intents give you full control over the payment UI but require custom frontend code, which negates the advantage of staying in Python."}, + {"question": "How do webhook handlers update UI state in real-time?", "answer": "When Stripe fires a webhook POST request to your API route, the handler verifies the signature, updates state variables server-side, and Reflex syncs those changes to the frontend over WebSocket automatically. No polling or manual re-renders required."}, + {"question": "What's the deployment process for a Stripe app built in Reflex?", "answer": "Run a single deploy command that provisions production infrastructure with HTTPS enabled by default. Stripe credentials live as encrypted environment variables that swap between test and live mode without code changes, keeping secret keys out of your codebase entirely."}, + {"question": "When should I consider self-hosting my Stripe integration?", "answer": "If your organization cannot route Stripe API keys through third-party cloud infrastructure due to compliance requirements, self-hosting keeps payment logic and credentials inside your own environment while maintaining an identical codebase to cloud deployments."}, + {"question": "Does Reflex support Stripe subscriptions or only one-time payments?", "answer": "Reflex supports both one-time payments and subscriptions through Stripe Checkout Sessions. The same integration architecture works for either payment model, as Checkout handles both billing types according to Stripe's documentation."}, + {"question": "How do I handle Stripe test mode vs live mode in production?", "answer": "Stripe credentials are stored as encrypted environment variables in Reflex, allowing you to swap between test and live mode without touching any code. The secret keys remain outside your codebase entirely, following Stripe's security best practices."}, + {"question": "What happens if a Stripe webhook fails signature verification?", "answer": "Reflex apps verify webhook signatures through the official Stripe SDK before any event handler executes, blocking unauthorized payment status changes at the framework level. If verification fails, the webhook is rejected and no state updates occur."}, + {"question": "Can I customize the Stripe Checkout page design?", "answer": "Stripe Checkout is a hosted payment page that Stripe controls, so extensive customization is limited. However, you can configure branding elements through your Stripe Dashboard, and the session creation in Reflex allows you to set success URLs, cancel URLs, and line item details."}, + {"question": "How does Reflex handle database updates for subscription status?", "answer": "When a Stripe webhook fires after payment completion, the webhook handler parses the PaymentIntent and writes subscription status directly to state, which can then be persisted to Reflex's built-in database layer. This all happens in Python within the same application context."}, + {"question": "What Stripe objects do I need to track for a subscription business?", "answer": "For subscriptions, you'll work with Checkout Sessions (for payment initiation), PaymentIntents (for tracking payment lifecycle), Customers (for storing user payment details), and Webhook Events (for asynchronous notifications). All of these are accessible through the Stripe Python SDK in Reflex."}, + {"question": "Can I process refunds through Reflex without writing custom JavaScript?", "answer": "Yes. Refund operations are handled through the Stripe Python SDK in your Reflex event handlers, with role-based access control determining which team members can trigger refunds. Everything stays in Python code that's version-controlled and auditable."}, + {"question": "How do I redirect users to Stripe Checkout from my Reflex app?", "answer": "Your event handler calls stripe.checkout.Session.create() to get a session URL, stores it in a state variable, and Reflex automatically detects the state change to redirect the browser. No JavaScript redirect logic or frontend callbacks are needed."}, + {"question": "What happens if a user abandons the Stripe Checkout page?", "answer": "When creating a Checkout Session, you specify a cancel URL that Stripe redirects to if the user abandons payment. Your Reflex app can render an appropriate page at that URL and handle the abandoned session however you choose, all in Python."}, + {"question": "Does Reflex support marketplace or multi-party payment flows with Stripe?", "answer": "Yes. Reflex handles Stripe's marketplace payouts and multi-party transactions at the enterprise level, with the same Python-based architecture used for standard checkouts. Compliance requirements and payment logic stay in version-controlled Python code whether you're building simple checkouts or complex marketplace flows."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Stripe integration with Python breaks when you need real-time UI updates for webhooks and multi-step payment flows +- Reflex handles Stripe Checkout Sessions, webhook verification, and state updates entirely in Python with no JavaScript +- Deploy production payment apps with automatic HTTPS and encrypted secrets using a single command +- Reflex is a full-stack Python framework that lets you build web apps with Stripe in pure Python, trusted by 40% of Fortune 500 companies + +## Why Python Developers Are Building Web Apps With Stripe in 2026 + +Stripe integration breaks Python apps in predictable ways. You have clean backend logic, solid data models, and then Stripe shows up - and suddenly you're duct-taping a React frontend to your Flask API just to render a checkout button. + +The real problem runs deeper than UI. Stripe integration demands multi-step state management: a user clicks pay, a payment intent gets created, a webhook fires asynchronously, and the UI needs to reflect all of it in real time. Python handles the server-side work well - Stripe provides Python SDKs that speak directly to its REST API and return clean JSON responses. But connecting that backend logic to a frontend users actually trust with their credit card? That's where traditional Python frameworks leave you stranded. + +This is why Python developers are increasingly reaching for full-stack Python frameworks in 2026. When state and event handlers all live in Python, webhook events update application state the same way any other server event does. No API glue. No context switching between two languages. The payment flow, the UI responding to it, and the backend processing it are all written in one place. + +## What You'll Build: A Python Web App Powered by Stripe + +[The app you're building](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) is a subscription checkout flow: users browse pricing tiers, select a plan, and get redirected to Stripe's hosted payment page. Once payment completes, a webhook fires, your app updates its state, and the user lands on a confirmation page showing their order details. + +The core integration pattern here is Stripe Checkout Sessions. When a user clicks a pricing tier, your app creates a Checkout Session server-side and redirects to Stripe's hosted payment page. Stripe handles card input, fraud detection, and 3DS, so your code only needs to manage what happens after. [According to Stripe's docs](https://docs.stripe.com/payments/checkout/how-checkout-works), Checkout supports both one-time purchases and subscriptions, so the same architecture works whether you're charging once or billing monthly. + +The UI side includes pricing cards, a checkout button, and a success page, all written in Python with no JavaScript required. What you end up with is a production-ready payment flow you can ship without rewriting it first. + +## Connecting Stripe to Your Reflex App + +The Stripe Python SDK drops cleanly into Reflex's backend architecture. Credentials are configured once at the project level and shared across all event handlers in your app. No per-file setup, no repeated config blocks. + +From there, the flow is straightforward. Your Reflex state class imports the Stripe SDK, event handlers call Stripe API methods like `checkout.Session.create`, and the returned URL or payment data gets stored as state variables. Because Reflex syncs state over WebSocket automatically, the frontend updates the moment state changes, no polling, no page refreshes. + +Webhooks fit naturally into this model too. Reflex API routes receive POST requests from Stripe, and the SDK verifies webhook signatures before your handler updates application state. [Stripe's best practices documentation](https://stripe.com/docs/webhooks/best-practices) stresses that verifying all incoming webhook requests is mandatory, and the SDK handles that with a single method call. + +| Stripe Object | Purpose | Reflex Implementation | +|---|---|---| +| Checkout Session | Redirect users to payment page | Created in event handler, URL stored in state | +| PaymentIntent | Track payment lifecycle | Retrieved via webhook handler, updates order state | +| Customer | Store user payment details | Associated with user model in database | +| Webhook Event | Asynchronous payment notifications | Handled by Reflex API route with signature verification | + +The [Stripe Python SDK](https://docs.stripe.com/get-started/development-environment?lang=python) gives you full access to Stripe's REST API from your Reflex backend, meaning every object above is available through standard Python method calls inside your state class. + +## Building the UI Around Stripe in Pure Python + +Building payment UI in Python means your pricing cards, subscribe buttons, and success pages all live as [Python functions tied to your logic](https://reflex.dev/blog/top-python-web-frameworks/). No HTML templates, no JSX, no separate stylesheet imports. Each component maps directly to what displays in the browser. + +The subscribe button triggers an event handler that calls `stripe.checkout.Session.create()` with your price ID, success URL, and cancel URL. The session URL returned by Stripe feeds into a state variable, and Reflex detects the change to redirect the browser automatically. No JavaScript redirect logic, no frontend callback wired to an API endpoint. The button click, the Stripe call, and the redirect all trace back to a single Python method. + +[According to Stripe's API docs](https://docs.stripe.com/api/checkout/sessions), a Checkout Session represents your customer's session as they pay through Checkout, and once payment succeeds it holds a reference to the Customer and PaymentIntent. That means after the webhook fires, your app has everything it needs to [update subscription status](https://reflex.dev/use-cases/finance/) directly from that object. + +### Post-Payment State Updates + +That webhook flow is where this approach really pays off: + +- Your webhook handler parses the PaymentIntent and writes subscription status back to state. +- The success page displays based on whatever state variables the handler set, unlocking premium features or showing order details automatically. +- The same developer who wrote the Stripe session config owns the confirmation page, same language, same file if needed, with zero coordination overhead. + +## Deploying Your Stripe App to Production + +[Deploying starts with one command](https://reflex.dev/hosting/) that pushes everything to production. Reflex Cloud handles HTTPS automatically, so your webhook endpoint URL is production-ready from day one, which is a hard requirement from Stripe's Dashboard configuration. + +Secrets stay out of your code entirely. Your Stripe secret key and webhook signing secret live as encrypted environment variables, swapped from test mode to live mode without touching a line of Python. [Stripe warns against embedding keys](https://docs.stripe.com/get-started/development-environment?lang=python), and this setup enforces that by default. + +For teams with stricter compliance needs, [self-hosting keeps credentials in your infrastructure](https://reflex.dev/blog/on-premises-deployment/). Either way, the deploy process stays consistent whether you're running one-time payments, subscriptions, or marketplace flows. + +## Accelerating Stripe App Development With Reflex's AI Builder + +Stripe payment apps follow predictable patterns: session creation, webhook verification, error handling, confirmation state. That boilerplate exists in every implementation, which makes it ideal territory for [Reflex's AI Builder](https://build.reflex.dev/). + +Prompt the builder with something like "build a subscription checkout with three pricing tiers" and it generates complete Python code covering Stripe SDK initialization, Checkout Session logic, pricing tier components, and webhook handlers. All of it is structured around the same state classes and event handler patterns covered earlier in this guide. No JavaScript, no throwaway prototype code. + +The Attach capability lets you connect your Stripe credentials directly inside the builder environment. Generated apps make live API calls during development, so you're testing real payment flows, not mock responses. Because integrations are configured at the project level, those credentials carry over automatically to any manually written features you add later. The AI-generated code and your own code share the same foundation from the start, so there's nothing to reconfigure as your app grows. + +## Enterprise Considerations for Stripe Apps Built With Reflex + +At the enterprise level, Stripe's role expands well beyond simple checkouts. Recurring billing, marketplace payouts, and high-value transactions each introduce compliance requirements that need careful handling at the framework level. + +Role-based access control (RBAC) determines which team members can access Stripe credentials, trigger refunds, or view payment data. [Permissions live in version-controlled Python code](https://reflex.dev/blog/structuring-a-large-app/) alongside the rest of your codebase. Audit logging for payment operations is handled through Reflex's built-in database layer, with no extra infrastructure required. + +> +Every Stripe webhook includes a Stripe-Signature header containing an HMAC signature. Always verify it before processing events. + +Reflex apps verify those signatures through the official Stripe SDK before any event handler executes, blocking unauthorized payment status changes at the framework level. + +For organizations that cannot route Stripe API keys through third-party cloud infrastructure, [self-hosting keeps credentials in your environment](https://reflex.dev/blog/enterprise-ready-ai-app-builder/). The codebase stays identical whether you deploy to Reflex Cloud or your own servers, so compliance requirements never force you to rewrite anything. + +## FAQ + +### Can I build a Stripe checkout flow without writing JavaScript? + +Yes. Full-stack Python frameworks like Reflex handle both frontend UI and backend payment logic in pure Python, so you never touch JavaScript while building production-ready checkout flows. + +### Stripe Checkout vs Payment Intents for Python web apps? + +Stripe Checkout provides a hosted payment page that handles card input, fraud detection, and 3DS automatically, making it the simplest integration. Payment Intents give you full control over the payment UI but require custom frontend code, which negates the advantage of staying in Python. + +### How do webhook handlers update UI state in real-time? + +When Stripe fires a webhook POST request to your API route, the handler verifies the signature, updates state variables server-side, and Reflex syncs those changes to the frontend over WebSocket automatically. No polling or page refreshes required. + +### What's the deployment process for a Stripe app built in Reflex? + +Run a single deploy command that provisions production infrastructure with HTTPS turned on by default. Stripe credentials live as encrypted environment variables that swap between test and live mode without code changes, keeping secret keys out of your codebase entirely. + +### When should I consider self-hosting my Stripe integration? + +If your organization cannot route Stripe API keys through third-party cloud infrastructure due to compliance requirements, self-hosting keeps payment logic and credentials inside your own environment while maintaining an identical codebase to cloud deployments. diff --git a/blog/build-python-web-app-with-zendesk.md b/blog/build-python-web-app-with-zendesk.md new file mode 100644 index 000000000..086bc7674 --- /dev/null +++ b/blog/build-python-web-app-with-zendesk.md @@ -0,0 +1,147 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Zendesk in 2026" +title_tag: "Build Python Web App With Zendesk 2026" +description: "Learn how to build a Python web app with Zendesk API in April 2026. Create support dashboards, manage tickets, and deploy production-ready tools without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Zendesk Python app, Zendesk API web app, support ticket Python, Zendesk integration, helpdesk Python app" + } +] +faq: [ + {"question": "Can I build a Zendesk web app without JavaScript?", "answer": "Yes. Frameworks like Reflex let you build the entire stack in Python, including the UI that wraps Zendesk API calls. You write event handlers that call Zenpy and manage state in Python classes, and the UI updates automatically without any JavaScript code."}, + {"question": "What's the best way to connect Zendesk to a Python web app in 2026?", "answer": "Install Zenpy (the official Python client), then configure your Zendesk subdomain and API token through Reflex's project-level integration settings. Once configured, those credentials are automatically shared across every app in your project, and you can call Zendesk operations directly from Python event handlers."}, + {"question": "Reflex vs Streamlit for building Zendesk dashboards?", "answer": "Streamlit's script rerun model causes the entire app to re-execute on every interaction, leading to memory leaks and slowdowns as ticket data scales. Reflex uses event-based state management where only the specific event handler runs, making it faster and more reliable for production support tools with real-time ticket updates."}, + {"question": "How long does it take to build a Zendesk ticket dashboard with Reflex?", "answer": "Most teams can build a working ticket queue with filters, detail views, and status updates in a few hours. Python developers who already know Zenpy can focus entirely on the app logic without learning frontend frameworks, since Reflex handles the UI layer in pure Python."}, + {"question": "When should I deploy a Zendesk app on-premises vs using Reflex Cloud?", "answer": "If your organization has strict compliance requirements around customer support data, self-hosted deployment keeps both your app and Zendesk API traffic inside your security perimeter. Reflex Cloud works well for standard deployments with multi-region scaling and built-in monitoring, while Helm chart support makes Kubernetes workflows straightforward for teams with existing infrastructure."}, + {"question": "What Zendesk API features can I access from a Python web app?", "answer": "The Zendesk Support API covers tickets, users, organizations, custom objects, workflow management, live chat, voice, and sales CRM. All of these endpoints are accessible through Python using the Zenpy client library, which you can integrate directly into your Reflex event handlers."}, + {"question": "How does Reflex handle real-time ticket updates without page reloads?", "answer": "Reflex uses event-based state management where user actions trigger Python event handlers that modify state and call the Zendesk API. When state changes, the UI automatically re-renders with fresh data without requiring manual DOM manipulation or separate fetch calls."}, + {"question": "Can multiple agents be assigned to a single Zendesk ticket?", "answer": "No. According to the Zendesk Tickets API, each ticket supports exactly one assignee at a time, which keeps assignment logic clean and predictable when building ticket routing workflows."}, + {"question": "What are common use cases for Python Zendesk web apps?", "answer": "Common use cases include ticket triage views that surface priority cases automatically, agent performance dashboards with real-time metrics, and internal escalation tools that route tickets based on custom business logic. Teams across finance, healthcare, and government are building these internal tools entirely in Python."}, + {"question": "Do I need to learn React or Vue to build a Zendesk dashboard?", "answer": "No. With Reflex, you can build both the backend Zendesk API logic and the frontend UI in pure Python without learning JavaScript frameworks. The same engineer can own the entire stack from API calls to user interface."}, + {"question": "How do I keep Zendesk API credentials secure in production?", "answer": "When deploying to Reflex Cloud, your Zendesk API credentials are stored as environment-level secrets that are never exposed in code. For self-hosted deployments, credentials stay inside your own security perimeter along with all Zendesk API traffic."}, + {"question": "What components does Reflex provide for building ticket dashboards?", "answer": "Reflex's component library includes tables, buttons, forms, modals, and badges out of the box, all configured in Python. A filterable ticket table becomes an rx.table wired to a state variable, and status dropdowns trigger event handlers that update Zendesk and refresh the UI automatically."}, + {"question": "Can I filter Zendesk tickets by custom criteria in my Python app?", "answer": "Yes. You can use Zenpy's search method to filter tickets by tags or other criteria, and implement UI controls in Reflex that let agents isolate tickets by status, priority, or any custom field supported by the Zendesk Search API."}, + {"question": "How does Reflex compare to code generators for building Zendesk apps?", "answer": "Unlike code generators that output throwaway JavaScript, Reflex produces maintainable Python code that teams can debug and extend. Your entire codebase stays in one language with clear ownership, making it easier to iterate on features as support workflows evolve."}, + {"question": "What happens when a Zendesk app needs to scale with increasing ticket volume?", "answer": "Reflex Cloud provides multi-region deployment and built-in monitoring that tracks API call performance as ticket volume grows. The event-based state model only runs specific handlers rather than re-executing the entire app, preventing the memory leaks and slowdowns common in script-rerun frameworks."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Reflex connects Python backend logic to production-ready UIs in one codebase without JavaScript + +- Build support dashboards with live Zendesk ticket queues, status updates, and agent assignments + +- Deploy with `reflex deploy` to Reflex Cloud or self-host for strict compliance requirements + +- Reflex outputs maintainable Python code that teams can debug, unlike throwaway JavaScript from code generators + +## Why Python Developers Are Building Web Apps With Zendesk in 2026 + +Zendesk's API surface is genuinely impressive. The [Support API](https://developer.zendesk.com/api-reference/) covers tickets, users, organizations, custom objects, workflow management, live chat, voice, and sales CRM. For Python teams, calling those endpoints is straightforward. The hard part is wrapping them in a UI that actually ships to production. + +That's where most projects stall. You have a Python backend pulling ticket data from Zendesk, but your team wants a dashboard, a ticket triage view, or an internal support tool. Historically, that meant reaching for React or Vue, writing two codebases, and suddenly your data science team is blocked on a frontend engineer's calendar. + +In 2026, Python developers are solving this differently. [Frameworks like Reflex](https://reflex.dev/blog/top-python-web-frameworks/) let you build the entire stack in Python, frontend included, so the same engineer who writes the Zendesk API logic can also build the UI around it without learning JavaScript. No split codebase. No context switching between languages. + +The use cases range from lightweight support dashboards to full ticket management portals. Teams across finance, healthcare, and government are already shipping [internal tools](https://reflex.dev/blog/internal-tool-builders/) this way, covering workflows like: + +- Ticket triage views that pull live queue data from Zendesk and surface priority cases automatically + +- Agent performance dashboards built entirely in Python with real-time metrics + +- Internal escalation tools that route tickets based on custom business logic + +## What You'll Build: A Python Web App Powered by Zendesk + +By the end of this guide, you'll have a working internal support dashboard where agents can view recent Zendesk tickets, inspect ticket details, update status, add comments, and assign tickets to team members. Per the [Zendesk Tickets API](https://developer.zendesk.com/api-reference/ticketing/tickets/tickets/), each ticket supports exactly one assignee at a time, so the assignment logic stays clean and predictable. + +The UI presents ticket data in a filterable table with controls for status and priority. When an agent makes a change, the app hits Zendesk's API and reflects the update in real time without a full page reload. + +Here's what the finished app covers: + +- A ticket queue table with filter controls for status and priority, so agents can isolate what needs attention through a [Python admin panel](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) without digging through unrelated requests. + +- A detail view showing full ticket context, requester info, and conversation history in one place. + +- Status updates and comment submission wired directly to Zendesk's API, with changes reflected immediately in the UI. + +- Single-assignee ticket routing built around your team's existing group structure. + +The pattern this guide uses for ticket management applies equally to user management, organization data, and help center content. To dig into this approach further, check out our [complete tutorial on building Python web apps](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/). Once you understand how Reflex handles state and API calls together, the same structure carries across any Zendesk resource. + +## Connecting Zendesk to Your Reflex App + +Getting Zendesk connected to your Reflex app starts with installing [Zenpy](https://developer.zendesk.com/documentation/ticketing/api-clients/python/), the actively maintained Python client for Zendesk Support, via pip. From there, you configure your Zendesk subdomain, email, and API token through Reflex's project-level integration settings. Because integrations are configured at the project level, those credentials are automatically shared across every app in the project. You set them once, and every app can reference them without duplicating config. + +The actual Zendesk calls live inside Reflex event handlers. These are Python functions that fire when a user takes an action in the UI, like clicking a filter or submitting a comment. State updates automatically, and the UI reflects the change without a page reload. No manual wiring required. + +Here's a quick reference for the Zendesk operations you'll use most: + +| Zendesk Operation | Zenpy Method | Use Case | +|---|---|---| +| Create ticket | `zenpy_client.tickets.create()` | Submit new support requests | +| List tickets | `zenpy_client.tickets()` | Display ticket dashboard | +| Update ticket | `zenpy_client.tickets.update()` | Change status or assignee | +| Search tickets | `zenpy_client.search()` | Filter by tags or criteria | +| Add comment | `ticket.comment = Comment()` | Agent replies to customers | + +With this foundation in place, you have everything you need to start building real Zendesk-powered functionality into your Python app. + +## Building the UI Around Zendesk in Pure Python + +Once your Zendesk connection is in place, building the UI is where Reflex's architecture genuinely earns its keep. Your app state lives in a Python class, holding variables like the current ticket list and whichever ticket the agent has selected. When state changes, the UI updates automatically, with no manual DOM manipulation, no `useState` hooks, and no JSX to debug. + +The component structure maps naturally to your app's layout. Reflex's [component library](https://reflex.dev/templates/) gives you tables, buttons, forms, modals, and badges out of the box, all configured in Python. A filterable ``[ticket table becomes an rx.table](https://reflex.dev/blog/using-table-component/) wired to a state variable. A status dropdown triggers an event handler that calls Zenpy, updates the ticket in Zendesk, and refreshes the displayed list in one step. + +### The Reactive Loop + +That reactive loop is what makes the state model worth understanding. As described in Reflex's component docs, the pattern stays consistent across every interaction: + +- A user action fires an event handler in your Python class. + +- The handler modifies state, calling Zenpy or updating a local variable as needed. + +- The UI refreshes with fresh data, no page reload or separate fetch call required. + +For a Zendesk app, an agent can change a ticket status and see the result immediately. The whole thing stays in Python, one language, one codebase, one engineer who can own both the Zendesk logic and the interface built around it. + +## Deploying Your Zendesk App to Production + +When your app is ready, [deploying to Reflex Cloud](https://reflex.dev/hosting/) takes a single command: `reflex deploy`. Your Zendesk API credentials stay secure as environment-level secrets, never exposed in code. Multi-region deployment keeps the app responsive for support teams spread across time zones, and built-in monitoring tracks API call performance as ticket volume scales. + +For organizations where customer support data has strict compliance requirements, [self-hosted deployment](https://reflex.dev/blog/on-premises-deployment/) keeps both your app and Zendesk API traffic inside your own security perimeter. Helm chart support makes Kubernetes and GitOps workflows straightforward to manage. + +The same deployment path works whether Zendesk is powering a simple ticket dashboard or a full omnichannel support backend. Deploy once, and your team owns the entire stack in Python. + +## FAQ + +### Can I build a Zendesk web app without JavaScript? + +Yes. Frameworks like Reflex let you build the entire stack in Python, including the UI that wraps Zendesk API calls. You write event handlers that call Zenpy and manage state in Python classes, and the UI updates automatically without any JavaScript code. + +### What's the best way to connect Zendesk to a Python web app in 2026? + +Install Zenpy (the official Python client), then configure your Zendesk subdomain and API token through Reflex's project-level integration settings. Once configured, those credentials are automatically shared across every app in your project, and you can call Zendesk operations directly from Python event handlers. + +### Reflex vs Streamlit for building Zendesk dashboards? + +Streamlit's script rerun model causes the entire app to re-execute on every interaction, leading to memory leaks and slowdowns as ticket data scales. Reflex uses event-based state management where only the specific event handler runs, making it faster and more reliable for production support tools with real-time ticket updates. + +### How long does it take to build a Zendesk ticket dashboard with Reflex? + +Most teams can build a working ticket queue with filters, detail views, and status updates in a few hours. Python developers who already know Zenpy can focus entirely on the app logic without learning frontend frameworks, since Reflex handles the UI layer in pure Python. + +### When should I deploy a Zendesk app on-premises vs using Reflex Cloud? + +If your organization has strict compliance requirements around customer support data, self-hosted deployment keeps both your app and Zendesk API traffic inside your security perimeter. Reflex Cloud works well for standard deployments with multi-region scaling and built-in monitoring, while Helm chart support makes Kubernetes workflows straightforward for teams with existing infrastructure. diff --git a/blog/how-to-build-dashboard-with-github.md b/blog/how-to-build-dashboard-with-github.md new file mode 100644 index 000000000..d75662aed --- /dev/null +++ b/blog/how-to-build-dashboard-with-github.md @@ -0,0 +1,156 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With GitHub in 2026" +title_tag: "Build a GitHub Dashboard in 2026" +description: "Learn how to build a GitHub dashboard with Python in April 2026. Track PRs, commits, and contributor activity with real-time data using PyGitHub and Reflex." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "GitHub dashboard Python, GitHub API dashboard, repository metrics, PR analytics Python, GitHub integration, developer dashboard" + } +] +faq: [ + {"question": "Can I build a GitHub dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full GitHub dashboards in pure Python using the PyGitHub library for data fetching and Reflex's built-in components for charts, tables, and stats. Your entire dashboard codebase stays in one language from API integration through deployment."}, + {"question": "GitHub dashboard Streamlit vs Reflex?", "answer": "Streamlit reruns your entire script on each user interaction, making stateful GitHub monitoring difficult to maintain as your dashboard grows. Reflex uses event-driven state management with WebSocket updates, so fresh commit data or PR status changes push to the UI automatically without full script reruns or polling workarounds."}, + {"question": "How do I handle GitHub API rate limits in production?", "answer": "Store API responses in Reflex state using background tasks that refresh data on a schedule rather than on every user click. GitHub's 5,000 requests per hour limit means polling on each interaction burns through your quota fast, but scheduled refreshes (hourly for commit velocity, daily for contributor lists) keep your dashboard responsive without hitting limits."}, + {"question": "What's the fastest way to deploy a GitHub dashboard in 2026?", "answer": "Run `reflex deploy` after wiring PyGitHub to your state class. Reflex Cloud handles packaging, multi-region routing, and dependency management in one command. Your Python code, GitHub credentials stored as environment variables, and all computed metrics deploy together without separate frontend build steps."}, + {"question": "When should I use real-time webhooks vs scheduled updates?", "answer": "Use GitHub webhooks for events that need immediate visibility (new PRs opened, issues closed, commits pushed) and scheduled background tasks for historical metrics that don't need second-by-second freshness (weekly commit velocity, monthly star growth). This split keeps your API quota healthy while your UI stays responsive where it matters."}, + {"question": "What GitHub metrics are most useful to track on a dashboard?", "answer": "The most valuable metrics include development velocity (commits per week), PR merge rate (percentage accepted), issue resolution speed, contributor activity patterns, and CI/CD pipeline health. These help teams spot workflow bottlenecks before they escalate and maintain visibility into repository health and code review workflows."}, + {"question": "Can I track multiple GitHub repositories in one Reflex dashboard?", "answer": "Yes. Reflex dashboards can pull data from multiple repositories simultaneously and display unified views of PR merge times, commit velocity, and contributor activity across your entire organization. You can filter by repository, time range, team member, or issue label without leaving the Python environment."}, + {"question": "What's the advantage of Reflex's WebSocket architecture for GitHub data?", "answer": "WebSocket connections push state updates from server to UI automatically when GitHub webhooks fire or scheduled jobs pull fresh data, eliminating the need for polling workarounds or separate Node.js services. This means real-time updates happen server-side and propagate instantly without manual re-rendering calls."}, + {"question": "How does PyGitHub integrate with Reflex applications?", "answer": "PyGitHub drops directly into Reflex projects as a single pip install, with event handlers inside your state class calling PyGitHub methods to fetch data and update state variables. Those variables then propagate to frontend components over WebSocket connections automatically without requiring any sync logic."}, + {"question": "Do I need to set up a separate backend API for my GitHub dashboard?", "answer": "No. Reflex handles both frontend and backend in pure Python, so you wire GitHub data directly to components without a separate API layer or JavaScript glue code. Libraries like PyGitHub integrate as plain Python function calls inside your event handlers."}, + {"question": "Can I use Reflex background tasks to refresh GitHub data automatically?", "answer": "Yes. Background tasks can periodically refresh GitHub data on a schedule and store results in computed vars or database tables that your components read from. This approach keeps API quota healthy while providing fast load times without polling on every user interaction."}, + {"question": "What happens when my Reflex dashboard grows beyond a simple prototype?", "answer": "Unlike Streamlit which reruns entire scripts on each interaction, Reflex uses event-driven state management that scales as dashboard complexity grows. Your ML engineer or data scientist can ship and maintain the same Python codebase from prototype through production without architectural rewrites."}, + {"question": "How do I display contributor leaderboards in a Reflex GitHub dashboard?", "answer": "Contributor leaderboards ranking team members by commit frequency or PR reviews completed map naturally to Reflex's built-in data table components with sortable columns. You fetch contributor data through PyGitHub and wire it to the table component in pure Python."}, + {"question": "Can I customize the time range for historical GitHub metrics?", "answer": "Yes. Reflex dashboards support interactive filtering by custom date range, allowing users to visualize commit velocity over specific quarters or track issue close rates across chosen periods. These time-series charts update based on user selections without requiring separate API configurations."}, + {"question": "What authentication method does Reflex use for GitHub API access?", "answer": "Reflex applications use GitHub personal access tokens stored as environment variables, which your state class reads when initializing the PyGitHub client. This project-level configuration means credentials are defined once and referenced automatically across all dashboard views without per-view reconfiguration."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build GitHub dashboards in pure Python with real-time data using PyGitHub and Reflex's WebSocket architecture + +- Track PR merge rates, commit velocity, and contributor activity without polling workarounds or separate API layers + +- Reflex handles frontend and backend in one codebase, avoiding the Streamlit rerun model or React context-switching + +- Deploy with `reflex deploy` and manage GitHub API credentials through environment variables to stay within rate limits + +- Reflex is an open-source Python framework that lets you build production-grade web apps without JavaScript + +## What You Can Build: GitHub Dashboard Overview + +A GitHub dashboard built with Reflex gives engineering managers and DevOps teams real-time visibility into repository health, team activity, and code review workflows. The GitHub API automatically fetches public repository data including stars, forks, contributor information, commit history, and pull request activity, so your dashboard stays current without manual updates. + +What does that actually look like in practice? Think of metrics like development velocity (commits per week), PR merge rate (percentage accepted), issue resolution speed, and growth trends that help teams spot workflow bottlenecks before they escalate. You can track contributor activity patterns, CI/CD pipeline health, and [PR merge times across multiple repositories](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) from one unified view. + +The real difference between a Reflex dashboard and a static reporting tool is interactivity. Users can filter by repository, time range, team member, or issue label and drill into specific metrics without leaving the Python environment. Need [a table of open PRs by assignee](https://reflex.dev/blog/using-table-component/)? Done. Want charts visualizing commit velocity over the past quarter? That too. + +Here is a quick breakdown of what you can build: + +- Repository health summaries showing stars, forks, and open issue counts updated on each page load. + +- Contributor leaderboards ranking team members by commit frequency or PR reviews completed. + +- CI/CD status monitors pulling pipeline run outcomes directly from the GitHub Actions API. + +- Time-series charts tracking issue close rates or release cadence across a custom date range. + +Because Reflex handles both the frontend and backend in pure Python, you wire data directly to components without a separate API layer or JavaScript glue code in between. + +## Why Python Developers Choose Reflex for GitHub Dashboards + +Python developers building GitHub dashboards face a familiar fork in the road: use Streamlit and hit a wall when you need real-time updates, or wire up a React frontend and suddenly you're context-switching between two languages. Reflex removes that choice entirely. + +The core advantage is architecture. When a GitHub webhook fires or a scheduled job pulls fresh commit data, Reflex's event handlers process that data server-side and push state updates to the UI over WebSockets automatically. No polling workarounds, no separate Node.js service sitting in the middle. Libraries like PyGitHub integrate directly into your event handlers as plain Python function calls. + +The component library matters here too. Reflex ships 60+ built-in components including cards, tables, and charts that map naturally to GitHub data shapes. A PR list becomes a data table. Commit velocity becomes a line chart. Repository stats become stat cards. You compose these in Python without writing JSX or configuring a BI tool. + +Compare that to the alternatives: + +- [Streamlit reruns your script on every interaction](https://reflex.dev/blog/reflex-streamlit/), making stateful GitHub monitoring painful to maintain at any meaningful scale. + +- [Dash's callback architecture](https://reflex.dev/blog/reflex-dash/) creates dependency spaghetti as dashboard complexity grows, turning simple feature additions into debugging sessions. + +- Lovable and similar generators produce JavaScript you cannot extend without pulling in a frontend engineer. + +With Reflex, your ML engineer or data scientist can ship and maintain the same codebase throughout the entire development lifecycle. + +## Connecting GitHub to Your Reflex App + +Getting GitHub data into a Reflex app starts with a single pip install. [PyGitHub](https://pypi.org/project/PyGithub/) is a Python library to access the GitHub REST API, managing resources like repositories, user profiles, and organizations, and it drops right into a Reflex project without any extra build steps. + +Authentication uses personal access tokens stored as environment variables, which your Reflex state class reads when initializing the PyGitHub client or hitting `https://api.github.com/` directly. Because Reflex supports project-level integration configuration, you define those credentials once and every dashboard view, whether that's an org overview, a repository drill-down, or contributor analytics, references them automatically. No per-view reconfiguration. + +From there, event handlers inside your state class call PyGitHub methods, fetch the data, and update state variables. Those variables propagate to frontend components over WebSocket connections without you writing any sync logic. + +### GitHub API Rate Limiting and Caching Strategies + +GitHub caps [authenticated requests at 5,000 per hour](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api), so polling on every user interaction will burn through that budget fast. The cleaner approach uses [Reflex background tasks to periodically refresh data](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) on a schedule, then stores results in computed vars or persists them to a database table that your components read from instead. Your users get fast load times, and your API quota stays healthy. + +## Key Dashboard Components for GitHub Data + +GitHub repository data maps cleanly to specific components based on what you're measuring. Development velocity, PR merge rate, issue resolution speed, and growth trends display well in line charts and area charts. Tabular data like pull request lists with status, reviewer assignments, and [merge times fits a data table](https://reflex.dev/blog/graphing-update/) with sortable columns. Stat cards handle high-level KPIs: open issue count, average PR review time, and star growth at a glance. + +State management ties these components together without boilerplate. A state class property calculates PR merge rate from raw API data, and every component referencing that variable updates automatically when the underlying data refreshes. No manual update calls needed. + +### Real-Time vs Periodic Data Updates + +GitHub webhooks produce real-time event streams (new PR opened, issue closed, commit pushed) that background tasks can process and reflect in dashboard state immediately. Scheduled background tasks handle historical metrics that do not need second-by-second freshness. Choosing the right update pattern per metric keeps your API quota healthy and your UI responsive. + +| GitHub Metric | Component Type | Update Pattern | Data Source | +|---|---|---|---| +| PR merge time | Line chart | Scheduled (hourly) | PyGitHub API | +| Open issues | Stat card | Real-time webhook | GitHub webhooks | +| Contributor list | Data table | Scheduled (daily) | REST API | +| Commit velocity | Area chart | Scheduled (hourly) | GraphQL API | + +## Deploying Your GitHub Dashboard to Production + +Deploying a Reflex dashboard is straightforward. Run `reflex deploy` and [Reflex Cloud packages your GitHub integration](https://reflex.dev/hosting/), PyGitHub dependencies, and computed metrics without a separate frontend build step. Multi-region routing keeps API calls fast for globally distributed teams. + +### Handling GitHub API Credentials in Production + +Store GitHub personal access tokens as environment variables in Reflex Cloud deployment settings or mount them as Kubernetes secrets for on-premises deployments. Never hardcode tokens in source code. + +A few other production considerations worth keeping in mind: + +- Cache GitHub API responses on the server side to avoid hitting rate limits during high-traffic periods. The GitHub REST API enforces a 5,000 requests per hour limit for authenticated users, so batching calls and storing results in state reduces unnecessary round trips. + +- Set up environment-specific configurations so your staging dashboard points to a test repository while production points to your live org, keeping test data out of real reporting. + +- Use Reflex's built-in state persistence to retain computed metrics across user sessions, so [visitors get instant data on page load](https://reflex.dev/blog/self-hosting-reflex-with-docker/). + +With credentials secured and caching in place, your dashboard is ready to serve real users reliably from day one. + +## FAQ + +### Can I build a GitHub dashboard without JavaScript? + +Yes. Reflex lets you build full GitHub dashboards in pure Python using the PyGitHub library for data fetching and Reflex's built-in components for charts, tables, and stats. Your entire dashboard codebase stays in one language from API integration through deployment. + +### GitHub dashboard Streamlit vs Reflex? + +Streamlit reruns your entire script on each user interaction, making stateful GitHub monitoring difficult to maintain as your dashboard grows. Reflex uses event-driven state management with WebSocket updates, so fresh commit data or PR status changes push to the UI automatically without full script reruns or polling workarounds. + +### How do I handle GitHub API rate limits in production? + +Store API responses in Reflex state using background tasks that refresh data on a schedule instead of on every user click. GitHub's 5,000 requests per hour limit means polling on each interaction burns through your quota fast, but scheduled refreshes (hourly for commit velocity, daily for contributor lists) keep your dashboard responsive without hitting limits. + +### What's the fastest way to deploy a GitHub dashboard in 2026? + +Run `reflex deploy` after wiring PyGitHub to your state class. Reflex Cloud handles packaging, multi-region routing, and dependency management in one command. Your Python code, GitHub credentials stored as environment variables, and all computed metrics deploy together without separate frontend build steps. + +### When should I use real-time webhooks vs scheduled updates? + +Use GitHub webhooks for events that need immediate visibility (new PRs opened, issues closed, commits pushed) and scheduled background tasks for historical metrics that don't need second-by-second freshness (weekly commit velocity, monthly star growth). This split keeps your API quota healthy while your UI stays responsive where it matters. diff --git a/blog/how-to-build-dashboard-with-mysql.md b/blog/how-to-build-dashboard-with-mysql.md new file mode 100644 index 000000000..bddd096ea --- /dev/null +++ b/blog/how-to-build-dashboard-with-mysql.md @@ -0,0 +1,181 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With MySQL in 2026" +title_tag: "Build MySQL Dashboard Python (April 2026)" +description: "Learn how to build a MySQL dashboard in April 2026 using Python. Connect your database, create interactive components, and deploy to production." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "MySQL dashboard Python, MySQL analytics dashboard, SQL dashboard, MySQL metrics Python, database dashboard MySQL" + } +] +faq: [ + {"question": "Can I build a MySQL dashboard without JavaScript in 2026?", "answer": "Yes. Python frameworks like Reflex let you build full MySQL dashboards without writing any JavaScript. Your queries, state management, and UI components all live in one Python codebase."}, + {"question": "How do I connect MySQL to a Reflex dashboard?", "answer": "You connect MySQL using any PyPI library (SQLAlchemy, mysql-connector-python, or PyMySQL) directly in a Reflex state class. The connection lives inside your Python backend and drives your UI automatically through event handlers and state variables."}, + {"question": "Reflex vs Streamlit for MySQL dashboards?", "answer": "Streamlit reruns your entire script on every interaction, causing memory leaks and making event-driven dashboards unreliable at scale. Reflex uses an event-based state model where specific user actions trigger specific query updates, keeping MySQL dashboards fast and responsive in production."}, + {"question": "What types of MySQL dashboards can you build with Reflex?", "answer": "You can build read-only analytics views showing sales trends and KPIs, full CRUD admin panels with inline editing, inventory trackers with live stock counts, operations dashboards monitoring queue depth, and executive reporting tools with filterable date ranges and role-based access controls."}, + {"question": "When should I deploy a MySQL dashboard on-premises instead of cloud hosting?", "answer": "If you work in finance, healthcare, or government, VPC and on-premises deployment options keep MySQL connections entirely within your network perimeter to satisfy compliance requirements without rebuilding the application."}, + {"question": "What MySQL libraries work with Reflex for dashboard development?", "answer": "SQLAlchemy, mysql-connector-python, and PyMySQL all work with Reflex since its backend runs pure Python. SQLAlchemy is the recommended default for most dashboards because it provides a database-agnostic ORM interface that makes complex data models easier to manage and query."}, + {"question": "How does Reflex handle real-time data updates in MySQL dashboards?", "answer": "Reflex uses an event-based state model where event handlers update state variables with fresh query results, and the UI re-renders automatically when those variables change. This keeps dashboards responsive without rerunning the entire application on every interaction."}, + {"question": "Can I use Reflex to build dashboards that write data back to MySQL?", "answer": "Yes. Reflex supports full CRUD operations, allowing you to build admin panels where users can create records, update order statuses, or modify data directly through the interface with inline editing capabilities."}, + {"question": "How do I secure MySQL credentials in a Reflex dashboard?", "answer": "MySQL credentials should be stored in environment variables, never hardcoded. For production deployments, you should also add SSL certificate configuration to encrypt connections in transit and set up connection pooling to handle concurrent user sessions."}, + {"question": "What are computed variables in Reflex and when should I use them?", "answer": "Computed variables transform raw query results into chart-ready formats, calculated totals, or filtered subsets without running additional queries. They're useful for client-side work like sorting, calculating totals, or formatting currency values before rendering, which minimizes database round-trips."}, + {"question": "How does Reflex compare to BI tools like Tableau or Metabase for MySQL dashboards?", "answer": "BI tools like Tableau or Metabase provide read-only visualizations and require custom extensions to build interactive workflows or write data back to MySQL. Reflex lets you build full interactive dashboards with CRUD operations entirely in Python without those limitations."}, + {"question": "Does Reflex support pagination for large MySQL result sets?", "answer": "Yes. Reflex supports pagination controls tied to LIMIT/OFFSET query parameters, which keeps result sets manageable for large tables while maintaining UI responsiveness without loading entire datasets at once."}, + {"question": "How do I monitor MySQL query performance in a Reflex dashboard?", "answer": "Reflex includes OpenTelemetry integration that provides distributed tracing across your application, including visibility into MySQL query latency and failure rates. Logs flow automatically into ClickHouse for centralized analysis."}, + {"question": "Can I filter MySQL data in real-time without causing performance issues?", "answer": "Yes. Reflex encourages parameterized queries with event handlers that use debounced inputs, reducing unnecessary database calls as users type. This pattern prevents SQL injection and keeps filtering responsive even on large datasets."}, + {"question": "What deployment command does Reflex use for MySQL dashboards?", "answer": "Running `reflex deploy` packages your backend query logic and frontend UI together, pushing everything to Reflex Cloud's infrastructure with multi-region scaling, CI/CD integration, and built-in monitoring without manual configuration."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build MySQL dashboards in pure Python using Reflex without writing JavaScript. + +- Reflex connects to MySQL using standard Python libraries like SQLAlchemy and PyMySQL. + +- The framework includes 60+ built-in components for tables, charts, and interactive controls. + +- Deploy with `reflex deploy` or use VPC/on-prem options for compliance requirements. + +- Reflex is an open-source Python framework for building production-grade web apps entirely in Python. + +## What You Can Build: MySQL Dashboard Overview + +Most MySQL data sits locked inside tables that only engineers can query. A dashboard changes that. Instead of writing SQL every time a stakeholder needs a number, you build one interface that surfaces the data automatically, keeps it updated, and lets your team interact with it without touching the database directly. + +With MySQL powering your backend, you can build a wide range of tools. Some teams need read-only analytics views showing sales trends, user growth, or inventory levels. Others need full CRUD dashboards where operators can create records, update order statuses, or flag transactions for review. Both are realistic targets. + +A few common builds: + +- Sales and revenue dashboards pulling from transactional tables to surface margin trends, conversion rates, and period-over-period comparisons. + +- [Admin panels](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) for managing users, orders, or content records with inline editing and role-based access controls. + +- Inventory trackers with live stock counts and low-threshold alerts to prevent fulfillment gaps. + +- Operations dashboards showing queue depth, job status, or pipeline health across distributed workflows. + +- Executive reporting views with filterable date ranges and KPI summaries for leadership review. + +The goal across all of these is the same: [visualize metrics in one unified view](https://www.metabase.com/dashboards/mysql) so teams make better decisions instead of keeping metrics buried in raw tables. + +## Why Python Developers Choose Reflex for MySQL Dashboards + +Building a MySQL dashboard in Python sounds straightforward until you hit the JavaScript wall. Your queries run fine, your data model is clean, and then you need a frontend. Suddenly you're managing two codebases, two languages, and a context switch that slows everything down. + +Reflex solves this by keeping the entire stack in Python. Your MySQL queries, your state management, your UI components: all of it lives in one language, one codebase, one mental model. There's no glue layer to maintain between a Flask API and a React frontend. + +The contrast with other options is worth noting: + +- BI tools like Tableau or Metabase give you read-only visualizations. You can't build interactive workflows or write data back to MySQL without custom extensions. + +- Low-code generators produce throwaway outputs that teams can't debug or extend without starting over. + +- Streamlit reruns your entire script on every interaction, which creates memory leaks and makes event-driven dashboards unreliable at scale. + +> + +"It's like Streamlit for adults. It's fast, it looks good, and we don't need to throw it away after prototyping." - Delta Global Head of Quant + +Reflex ships 60+ built-in components with full CSS control, so [dashboards](https://reflex.dev/templates/finance-dashboard/) look production-ready without custom design work. And because it's a real framework (not a code generator), what you build is something your team can actually maintain. + +## Connecting MySQL to Your Reflex App + +Reflex's backend runs pure Python, which means any MySQL library available on PyPI works out of the box. There's no adapter layer, no API translation, no separate backend service to stand up. You connect to MySQL the same way you would in any Python script, except that connection lives inside a Reflex state class that drives your UI automatically. + +One practical advantage: Reflex's project-level integration configuration lets you define your MySQL credentials once and share them across every app in your workspace. If you're building multiple dashboards against the same database, you're not re-entering connection strings for each one. + +### MySQL Connection Libraries + +Three libraries cover most use cases, and choosing between them depends on how much abstraction you want: + +- SQLAlchemy: the most common choice for dashboard work. It gives you [a database-agnostic ORM interface](https://www.pingcap.com/article/comparing-python-libraries-mysql-integration-2024/) that abstracts raw SQL into Python objects, making complex data models easier to manage and query. + +- mysql-connector-python: Oracle's official driver for direct database API access. Good when you want precise control over queries without ORM overhead. + +- PyMySQL: a pure Python alternative with minimal dependencies, useful in restricted environments where you'd rather avoid compiled extensions. + +SQLAlchemy is the right default for most dashboards. + +### State Management Pattern + +In Reflex, a state class is where your database logic lives. You define query methods directly on the class, call them from event handlers, and store results as state variables. When an event handler updates a variable, the UI updates automatically with fresh data. + +Computed variables are particularly useful here: they let you convert raw query results into chart-ready formats, calculated totals, or filtered subsets without running additional queries. The data flow stays linear and traceable, which matters when stakeholders ask why a number looks wrong. + +## Key Dashboard Components for MySQL Data + +MySQL's relational structure maps naturally to Reflex's component library. Each data shape has a component built for it, and Reflex's reactive state model handles the wiring automatically when database values change. + +### Data Display Components + +| MySQL Data Type | Recommended Component | Use Case | +|---|---|---| +| SELECT results (tabular) | rx.data_table | Transaction logs, user lists, inventory records | +| Aggregated metrics | rx.recharts (bar, line, area) | Revenue trends, query performance, growth metrics | +| Key performance indicators | rx.stat | Active users, total sales, error counts | +| Time-series data | rx.recharts.line_chart | Traffic patterns, database load, historical comparisons | +| Hierarchical relationships | rx.tree | Category structures, organizational charts, nested data | + +Reflex's 60+ built-in components cover these patterns without third-party dependencies. Charts connect directly to state variables, so when your query result updates, the visualization updates with it. + +### Interactive Controls + +Filtering and search are where Reflex's state model earns its keep. Event handlers receive user input, pass it into parameterized queries, and update state with fresh results. Parameterized queries are the natural pattern Reflex encourages, which means SQL injection prevention comes built into the architecture instead of as an afterthought. + +A few patterns that work well for MySQL dashboards: + +- [Date range pickers](https://reflex.dev/templates/real-time-sales-dashboard/) that feed start and end values into WHERE clauses, letting users scope data to any time window without writing additional query logic + +- Search inputs that filter text columns with debounced event handlers, reducing unnecessary database calls as users type + +- Dropdown selectors that switch between aggregation dimensions, such as grouping revenue by region, product, or sales rep + +- Pagination controls tied to LIMIT/OFFSET query parameters, keeping result sets manageable for large tables + +Computed vars handle the client-side work: sorting a loaded result set, calculating totals, or formatting currency values before display. This keeps [database round-trips](https://reflex.dev/templates/database-visualization/) to a minimum while keeping the UI responsive. + +## Deploying Your MySQL Dashboard to Production + +When your dashboard is ready, deployment is a single command. Running `reflex deploy` packages your backend query logic and frontend UI together, [pushing everything to Reflex Cloud's infrastructure](https://reflex.dev/blog/self-hosting-reflex-with-docker/) without manual configuration. You get multi-region scaling, CI/CD integration, and built-in monitoring out of the box. + +For teams with stricter data requirements, the architecture changes. Finance, healthcare, and government deployments often cannot route MySQL traffic through shared cloud infrastructure. [VPC and on-premises hosting options](https://reflex.dev/blog/on-premises-deployment/) keep database connections entirely within your network perimeter, satisfying compliance requirements without rebuilding the application. + +### Database Connection Security + +MySQL credentials belong in environment variables, never hardcoded. For production workloads, add SSL certificate configuration to encrypt connections in transit and set up connection pooling to handle concurrent user sessions without exhausting database resources. + +### Monitoring and Observability + +OpenTelemetry integration gives you distributed tracing across your application, including visibility into MySQL query latency and failure rates. Logs flow automatically into ClickHouse for centralized analysis. When a dashboard query starts running slow, you will know before your users do. + +## FAQ + +### Can I build a MySQL dashboard without JavaScript in 2026? + +Yes. Python frameworks like Reflex let you build full MySQL dashboards without writing any JavaScript. Your queries, state management, and UI components all live in one Python codebase. + +### How do I connect MySQL to a Reflex dashboard? + +You connect MySQL using any PyPI library (SQLAlchemy, mysql-connector-python, or PyMySQL) directly in a Reflex state class. The connection lives inside your Python backend and drives your UI automatically through event handlers and state variables. + +### Reflex vs Streamlit for MySQL dashboards? + +Streamlit reruns your entire script on every interaction, causing memory leaks and making event-driven dashboards unreliable at scale. Reflex uses an event-based state model where specific user actions trigger specific query updates, keeping MySQL dashboards fast and responsive in production. + +### What types of MySQL dashboards can you build with Reflex? + +You can build read-only analytics views showing sales trends and KPIs, full CRUD admin panels with inline editing, inventory trackers with live stock counts, operations dashboards monitoring queue depth, and executive reporting tools with filterable date ranges and role-based access controls. + +### When should I deploy a MySQL dashboard on-premises instead of cloud hosting? + +If you work in finance, healthcare, or government, VPC and on-premises deployment options keep MySQL connections entirely within your network perimeter to satisfy compliance requirements without rebuilding the application. diff --git a/blog/how-to-build-dashboard-with-plaid.md b/blog/how-to-build-dashboard-with-plaid.md new file mode 100644 index 000000000..8e5ef193e --- /dev/null +++ b/blog/how-to-build-dashboard-with-plaid.md @@ -0,0 +1,143 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Plaid in 2026" +title_tag: "Build a Plaid Dashboard in 2026" +description: "Learn how to build a production-ready Plaid dashboard in pure Python. Complete guide covering API integration, deployment, and best practices for April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Plaid dashboard Python, Plaid API dashboard, fintech dashboard, banking analytics Python, financial data dashboard" + } +] +faq: [ + {"question": "Can I build a Plaid dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full Plaid integrations in pure Python with no JavaScript required. The framework handles your Plaid API calls, transaction processing, and interactive UI components all in one Python codebase, so you skip the separate frontend repo entirely."}, + {"question": "Plaid dashboard Reflex vs Streamlit?", "answer": "Streamlit works for quick prototypes but struggles with production Plaid dashboards because its script rerun model causes memory leaks when processing large transaction datasets. Reflex uses event-based state management that handles real-time webhook updates from Plaid without freezing the UI, and ships with polished components that look professional enough for client-facing applications."}, + {"question": "How long does Plaid dashboard implementation take?", "answer": "Most Python developers complete the initial setup in 2-3 hours using Reflex's built-in components for transaction tables, balance cards, and spending charts. Full deployment with webhook handlers and production credential rotation typically takes 1-2 days depending on how many account types you're aggregating."}, + {"question": "What's the difference between Plaid Sandbox and Production environments?", "answer": "Plaid keeps Sandbox and Production completely separate, meaning items created during testing cannot migrate to live environments. You need explicit environment variable switching between credential sets at deploy time to avoid accidentally exposing production keys during development cycles."}, + {"question": "What types of financial data can I access through Plaid's API?", "answer": "Plaid provides access to account balances, up to 24 months of categorized transaction data with merchant names and categories, recurring payment detection, identity verification, income verification, and fraud detection capabilities. For dashboard builders, the Transactions API is most relevant as it delivers cleaned, organized spending data ready for analytics."}, + {"question": "Do I need separate frontend developers to build a Plaid dashboard with Reflex?", "answer": "No, Reflex lets Python developers build complete Plaid dashboards without frontend specialists. The framework handles API calls, event handlers, and UI components all in one Python file, producing readable code that data engineers and domain experts can maintain without JavaScript expertise."}, + {"question": "How does Reflex handle real-time Plaid webhook notifications?", "answer": "Reflex uses async event handlers and background jobs to process incoming Plaid webhook payloads without freezing the UI. When Plaid pushes transaction update notifications, the background tasks update state and re-render components while users continue interacting with the dashboard."}, + {"question": "Can I deploy a Plaid dashboard on-premises for compliance requirements?", "answer": "Yes, Reflex supports self-hosting options including VPC and on-premises deployments. This allows financial services teams to isolate dashboard infrastructure within private networks, satisfying compliance restrictions that prohibit external SaaS hosting of financial credentials."}, + {"question": "What Python version do I need to build a Plaid dashboard with Reflex?", "answer": "You need Python 3.10 or higher to run Reflex locally. The installation takes just three commands, and Plaid's official Python library installs via pip with no additional build tools required."}, + {"question": "How does Plaid categorize transactions automatically?", "answer": "Plaid uses AI-enhanced categorization to turn raw transactions into enriched records with merchant names, spending categories, and counterparty data. This categorization happens automatically and provides up to 24 months of historical transaction data organized and ready for dashboard visualization."}, + {"question": "Can I aggregate data from multiple bank accounts in one Plaid dashboard?", "answer": "Yes, Plaid dashboards can surface data across multiple linked accounts from different financial institutions. This gives users a single view of all their accounts without logging into each bank separately, making it ideal for personal finance tracking, portfolio management, and cash flow monitoring."}, + {"question": "What's included in Reflex's built-in components for financial dashboards?", "answer": "Reflex includes 60+ built-in components covering tables, charts, stat cards, and filters that handle most financial dashboard patterns. For specialized needs, you can wrap any React charting library without leaving Python, giving you flexibility while maintaining a pure Python codebase."}, + {"question": "How do I manage Plaid API credentials securely in Reflex?", "answer": "Reflex's project-level configuration stores your Plaid client ID, secret key, and environment settings once, and every app inside that project inherits those credentials. This eliminates copying API keys across files and supports environment-specific variables to prevent accidental exposure of production credentials during testing."}, + {"question": "What are the main use cases for building a Plaid dashboard?", "answer": "The three primary audiences are consumers tracking personal finances across accounts, fintech teams building internal analytics tools for cash flow monitoring, and financial advisors managing client portfolios. All need interactive views of financial data without manual CSV exports or logging into multiple bank portals."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build production Plaid dashboards in pure Python with Reflex, handling API calls and UI in one file. + +- Plaid provides 24 months of categorized transaction data, account balances, and recurring payment detection via clean APIs. + +- Reflex's state management handles webhook updates and real-time data refreshes without frontend complexity. + +- Deploy with `reflex deploy` while maintaining VPC/on-prem options for financial compliance requirements. + +- Reflex is a full-stack Python framework that outputs readable code teams can maintain without frontend expertise. + +## What You Can Build: Plaid Dashboard Overview + +Plaid is a financial data infrastructure layer that connects apps to users' bank accounts through a clean API. It covers account verification, transaction data, identity verification, income verification, and fraud detection. For dashboard builders, the most relevant piece is the Transactions API: [Plaid provides 24 months of transaction history](https://plaid.com/products/transactions/), cleaned up, organized, and ready to use. + +What does that unlock in practice? A Plaid dashboard can surface account balances, categorized transactions, recurring payment detection, and spending trends across multiple linked accounts. Check out our [Reflex dashboard](https://reflex.dev/templates/finance-dashboard/) template to see one in action. You're working with read-only financial data, which keeps the scope focused on analytics instead of banking operations. + +The use cases split into three broad audiences: + +- Consumers tracking personal finances and monthly budgets who want a single view across all their accounts without logging into each bank separately. + +- Fintech teams [building internal analytics tools](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) for cash flow monitoring, where raw transaction feeds need to become something a non-technical stakeholder can actually read. + +- [Financial advisors watching client account activity](https://reflex.dev/use-cases/finance/) across portfolios, where aggregating data from dozens of accounts into one coherent view saves hours of manual work. + +Each of these wants roughly the same thing: a clean, interactive view of financial data without the user needing to export a CSV or log into five different bank portals. The Plaid API handles the data plumbing, and your job is building the interface that makes it readable and actionable. + +## Why Python Developers Choose Reflex for Plaid Dashboards + +Building a Plaid dashboard in Python usually hits a wall fast. The data layer is straightforward enough, but building a polished, interactive UI requires either learning React or stitching together Streamlit widgets that top out at "functional but ugly." Reflex removes that wall entirely. + +With Reflex, your Plaid API calls, event handlers, and UI components all live in one Python file. No separate frontend repo, no JavaScript build pipeline, no context-switching between languages mid-feature. The 60+ built-in components include tables, charts, stat cards, and filters that cover most financial dashboard patterns out of the box. When you need something more specialized, you can wrap any React charting library without leaving Python. + +Worth noting too: the output is readable code your team can actually maintain. Code generation tools like Lovable or Bolt produce JavaScript bundles that data engineers and quant developers cannot debug. Reflex outputs Python that domain experts can open, read, and modify without a frontend specialist in the room. That matters when a stakeholder wants to adjust a spending category filter on a Friday afternoon. + +Getting started takes three commands via the installation guide. Python 3.10 or higher is all you need locally. + +## Connecting Plaid to Your Reflex App + +Plaid offers an [official Python library](https://plaid.com/docs/api/libraries/) installable via pip, which means setup is a single command instead of a REST client you build yourself. Once installed, it drops straight into Reflex's Python backend with no separate API service layer required. + +The integration fits naturally into Reflex's state management model. You define a state class that holds your Plaid responses: account balances, transaction lists, connection status. Event handlers call the Plaid endpoints and write results back into state, which the UI components read automatically. [Plaid's API uses JSON over HTTP](https://plaid.com/docs/api/), so responses parse cleanly into Python dictionaries without extra serialization logic. + +For credential management, Reflex's project-level configuration stores your Plaid client ID, secret key, and environment settings once. Every app inside that project inherits those credentials, so you avoid copying and pasting API keys across multiple files. + +Where things get interesting is with webhooks. When Plaid pushes a transaction update notification, you want that [processed in the background](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) without freezing the UI. Reflex's async event handlers and background jobs handle exactly this pattern, letting incoming webhook payloads update state and re-render components while the user continues interacting with the dashboard. + +## Key Dashboard Components for Plaid Data + +Three component types cover the bulk of what a Plaid dashboard needs. Each maps cleanly to what Plaid's API actually returns. + +### Transaction Tables and Filtering + +Plaid's AI-enhanced categorization turns raw transactions into enriched records with merchant names, categories, and counterparty data, making the transaction table the core UI primitive. A well-built [transaction table](https://reflex.dev/blog/using-table-component/) handles pagination natively, while computed vars calculate monthly totals or category breakdowns server-side. Filters for date range or account type update Python state and [re-render only the affected rows](https://reflex.dev/blog/using-ag-grid-in-reflex/) automatically. + +### Balance Cards and Account Summaries + +Account balance data maps directly to stat card components showing current balance, available credit, and account type. A grid layout stacks one card per connected institution, and computed vars sum across account types to surface aggregate net worth or total debt without any client-side math. + +### Spending Charts and Trend Visualization + +[Plaid delivers 24 months of enriched data](https://plaid.com/use-cases/personal-financial-insights/), including merchant names, categories, and locations. Charts reading directly from state vars mean switching a date filter updates the visualization without a page reload. + +| Dashboard Component | Plaid Data Type | Reflex Component | Use Case | +|---|---|---|---| +| Transaction list | Transactions API enriched data | rx.data_table with pagination | Display categorized spending history with filters | +| Balance cards | Accounts API balance data | rx.card with rx.stat | Show real-time account balances across institutions | +| Spending chart | Aggregated transactions by category | Plotly wrapped chart | Visualize spending patterns over time | +| Recurring payments | Transaction counterparty analysis | rx.list with rx.badge | Identify subscription charges and bills | + +## Deploying Your Plaid Dashboard to Production + +When you're ready to ship, a single `reflex deploy` command packages your Plaid connection logic, transaction processing, and webhook handlers together with no separate frontend pipeline required. [Deploy with Reflex hosting](https://reflex.dev/hosting/) for instant production access. + +> + +Plaid keeps Sandbox and Production as fully separate environments. Items created in Sandbox cannot move to Production, so your environment variables need to switch explicitly between credential sets at deploy time. + +Here are a few key considerations to keep in mind before going live: + +- Plaid credentials must be explicitly rotated between Sandbox and Production environments. Storing them as environment-specific variables prevents accidental exposure of live keys during testing cycles. + +- For financial services teams with strict compliance requirements, [self-hosting options covering VPC and on-premises deployments](https://reflex.dev/blog/on-premises-deployment/) let you isolate dashboard infrastructure within private networks, which satisfies restrictions that prohibit external SaaS hosting of financial credentials. + +- Built-in monitoring tracks Plaid API response times and webhook delivery without requiring additional APM setup, keeping your observability footprint light. + +Keeping these production concerns in mind early saves major rework later, especially when handling live bank credentials and real user financial data. + +## FAQ + +### Can I build a Plaid dashboard without JavaScript? + +Yes. Reflex lets you build full Plaid integrations in pure Python with no JavaScript required. The framework handles your Plaid API calls, transaction processing, and interactive UI components all in one Python codebase, so you skip the separate frontend repo entirely. + +### Plaid dashboard Reflex vs Streamlit? + +Streamlit works for quick prototypes but struggles with production Plaid dashboards because its script rerun model causes memory leaks when processing large transaction datasets. Reflex uses event-based state management that handles real-time webhook updates from Plaid without freezing the UI, and ships with polished components that look professional enough for client-facing applications. + +### How long does Plaid dashboard implementation take? + +Most Python developers complete the initial setup in 2-3 hours using Reflex's built-in components for transaction tables, balance cards, and spending charts. Full deployment with webhook handlers and production credential rotation typically takes 1-2 days depending on how many account types you're aggregating. + +### What's the difference between Plaid Sandbox and Production environments? + +Plaid keeps Sandbox and Production completely separate, meaning items created during testing cannot migrate to live environments. You need explicit environment variable switching between credential sets at deploy time to avoid accidentally exposing production keys during development cycles. diff --git a/blog/how-to-build-dashboard-with-snowflake.md b/blog/how-to-build-dashboard-with-snowflake.md new file mode 100644 index 000000000..1bd2dae97 --- /dev/null +++ b/blog/how-to-build-dashboard-with-snowflake.md @@ -0,0 +1,142 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Dashboard With Snowflake in 2026" +title_tag: "Build Snowflake Dashboard Guide April 2026" +description: "Learn how to build a dashboard with Snowflake in April 2026. Complete guide to connecting Snowflake data warehouses and creating production-ready dashboards." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Snowflake dashboard Python, Snowflake analytics dashboard, data warehouse dashboard, Snowflake Python metrics" + } +] +faq: [ + {"question": "Can I build a Snowflake dashboard without JavaScript?", "answer": "Yes. Reflex lets you build full Snowflake dashboards in pure Python, including queries, state management, and UI components, all in the same codebase. The Snowflake Connector for Python handles data access, while Reflex's 60+ built-in components cover charts, tables, and filters without requiring frontend development skills."}, + {"question": "Snowflake dashboard Streamlit vs Reflex?", "answer": "Streamlit works for quick prototypes but breaks down with complex Snowflake workflows—its rerun model causes memory leaks, and there's no event-based interaction or server push for real-time updates. Reflex handles full read-write workflows with Snowflake, supports production-grade authentication and deployment, and customers describe it as \"Streamlit for adults\" because you don't have to throw it away after prototyping."}, + {"question": "How do I connect Snowflake to a Reflex dashboard?", "answer": "Install the Snowflake Connector for Python via pip, then configure your account identifier, warehouse, and database credentials at the project level in Reflex. Your Snowflake queries run directly in Reflex event handlers as Python code, with no middleware or API gateway required—the connection setup works the same way it would in any Python script."}, + {"question": "What's the fastest way to deploy a Snowflake dashboard in 2026?", "answer": "Run `reflex deploy` for managed cloud hosting that handles your Python backend, Snowflake connector, and infrastructure in one command. For regulated industries requiring data residency, deploy on-premises using Reflex's Helm charts for Kubernetes to keep all Snowflake query execution within your own network and satisfy compliance requirements."}, + {"question": "What types of dashboards can I build with Snowflake and Reflex?", "answer": "You can build financial analytics dashboards for real-time P&L data, operational intelligence tools like treasury dashboards for warehouse performance metrics, data quality monitors and machine learning dashboards for pipeline health, and executive reporting interfaces that combine Snowflake query results with custom business logic. Reflex supports full read-write workflows, so dashboards can both display data and let users trigger actions or update configurations."}, + {"question": "Do I need frontend development experience to build a Snowflake dashboard with Reflex?", "answer": "No. Reflex provides 60+ built-in components for charts, tables, forms, and filters that work entirely in Python, and you can wrap any React component in pure Python when needed. Analytics engineers who write dbt models and Snowflake transformations can extend that same Python knowledge into a full web interface without learning JavaScript."}, + {"question": "How does Reflex handle authentication for Snowflake connections?", "answer": "Reflex supports password authentication, key pair authentication, and OAuth for Snowflake connections. The authentication method is configured once at the project level along with your account identifier, warehouse, and database settings, creating a single source of truth shared across every app in the project."}, + {"question": "Can I use computed metrics in my Snowflake dashboard?", "answer": "Yes. Reflex's computed vars automatically derive metrics like cost per query, average execution time, and storage growth rate from raw Snowflake data in state. When upstream state changes, only components that depend on those vars re-render, keeping your dashboard current without manual DOM updates or polling logic."}, + {"question": "What Snowflake operations can I perform from a Reflex dashboard?", "answer": "You can run all standard Snowflake operations including querying tables, executing stored procedures, and performing read-write workflows. The Snowflake Connector for Python provides the full interface, and because Reflex runs a Python backend natively, these operations work the same way they would in any Python script."}, + {"question": "How do I handle real-time data updates in a Snowflake dashboard?", "answer": "Reflex supports event-based interaction and server push for real-time updates, unlike tools like Streamlit that use a rerun model. For time-series data like credit consumption or query latency, you can use Recharts-based line and area charts with full control over axes and formatting, and for live data streams you can use text components or custom components."}, + {"question": "Can I deploy a Snowflake dashboard on-premises for compliance?", "answer": "Yes. Finance, healthcare, and government teams can deploy Reflex applications on-premises using Helm charts for Kubernetes, keeping all code execution and Snowflake access entirely within their own infrastructure. This satisfies data residency requirements and compliance rules without query results ever leaving your environment."}, + {"question": "What's the difference between Reflex and code generation tools for Snowflake dashboards?", "answer": "Code generation tools output JavaScript that requires frontend expertise to maintain, while Reflex gives you a real framework with standardized patterns for state management, routing, and component composition. When debugging production issues, your engineers read Python that maps directly to business logic rather than transpiled artifacts they didn't write."}, + {"question": "How does Reflex handle large Snowflake query results in tables?", "answer": "Reflex's table and data table components handle sorting, pagination, and column configuration natively, making them suitable for warehouse query history, user activity logs, and cost attribution tables. These components are designed to work with structured Snowflake result sets without requiring custom client-side logic."}, + {"question": "What infrastructure does Reflex Cloud provide for Snowflake dashboards?", "answer": "Reflex Cloud provides multi-region support, GitHub Actions and GitLab CI integration, and built-in monitoring without extra configuration. The managed hosting handles your Python backend, Snowflake connector, compiled frontend, and infrastructure provisioning through a single `reflex deploy` command."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build Snowflake dashboards in pure Python with Reflex without writing JavaScript + +- Reflex connects to Snowflake using the Python SDK directly in your backend code + +- Python developers read and debug production dashboards faster than JavaScript alternatives + +- Reflex is an open-source Python framework that lets you build full-stack web apps entirely in Python + +## What You Can Build: Snowflake Dashboard Overview + +Snowflake sits at the center of how Global 2000 enterprises store and query their most valuable data, with deep roots in [financial services](https://reflex.dev/use-cases/finance/), healthcare, and retail. When you connect it to a Python app, that data stops living in a warehouse and starts becoming something people can actually act on. + +Here's what teams are building: + +- [Financial analytics dashboards](https://reflex.dev/templates/finance-dashboard/) that pull real-time P&L data, track revenue by segment, and let portfolio managers filter results without touching SQL + +- Intelligence tools like a [treasury dashboard](https://reflex.dev/templates/treasury-dashboard/) that surface warehouse performance metrics and query costs, giving data engineers visibility into what's consuming credits + +- Data quality monitors and [machine learning dashboards](https://reflex.dev/templates/machine-learning-model-dashboard/) that track pipeline health and flag anomalies as they appear, instead of hours later in a morning report + +- Executive reporting interfaces and [real-time sales dashboards](https://reflex.dev/templates/real-time-sales-dashboard/) that combine Snowflake query results with custom business logic, formatted for leadership instead of analysts + +What makes this combination worth paying attention to is that Snowflake supports full read-write workflows. Your dashboard can display data and let users trigger actions, update configurations, or modify warehouse settings through the same interface. One app handles both directions. + +## Why Python Developers Choose Reflex for Snowflake Dashboards + +Python developers working with Snowflake already own the hard part: the data layer. The recurring challenge is getting insights out of the warehouse and into an interface that non-technical stakeholders can actually use. That's where the frontend gap appears, and where most teams lose time. + +### Single Python Codebase for Full Stack Development + +Reflex keeps everything in one language. Your Snowflake queries, state management, and UI components all live in the same Python file, with no context switching between languages or build systems. Analytics engineers who write dbt models and Snowflake transformations can extend that same Python knowledge into building full web interfaces. The 60+ built-in components cover charts, tables, forms, and filters out of the box, and you can wrap any React component in pure Python when you need something more specialized. You can also check out [Reflex templates](https://reflex.dev/templates/) for ready-made examples. No JavaScript required at any point. + +### Framework Foundation vs Code Generation + +> + +"It's like Streamlit for adults. It's fast, it looks good, and we don't need to throw it away after prototyping." - Delta Global Head of Quant + +Code generation tools that output JavaScript introduce a different problem: you get something that looks like a dashboard but requires frontend expertise to maintain. Reflex gives you a real framework with standardized patterns for state management, routing, and component composition. When a Snowflake query returns unexpected results overnight, your engineer reads Python that maps directly to business logic, not transpiled artifacts. That's the practical difference between a component system built for Python teams versus generated code your team didn't write and can't confidently modify. + +## Connecting Snowflake to Your Reflex App + +The connection setup is simpler than most teams expect. Because Reflex runs a Python backend natively, you connect to Snowflake the same way you would in any Python script, with no separate middleware or API layer required. + +### Python SDK Integration Without Additional Services + +The [Snowflake Connector for Python](https://docs.snowflake.com/en/developer-guide/python-connector/python-connector) provides a full interface for connecting to Snowflake and running all standard operations, from querying tables to executing stored procedures. It serves as a programming alternative to JDBC or ODBC drivers, and installs via pip like any other dependency. For detailed examples and best practices, Snowflake's [official connector documentation](https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example) covers authentication patterns and query optimization. Drop it into a Reflex project, wire it into a state class and event handler, and your Snowflake queries become first-class application logic. No external service, no gateway layer. + +### Project-Level Integration Configuration + +Where Reflex goes further is in how it handles credentials. Instead of configuring Snowflake connection parameters per app, Reflex's project-level integration configuration defines your account identifier, warehouse, database, and authentication method once and shares it across every app in the project. Whether you're using password auth, key pair, or OAuth, that configuration lives in one place. Teams building several Snowflake dashboards on the same project get a single source of truth, which reduces configuration drift and limits the surface area for credential mismanagement. + +## Key Dashboard Components for Snowflake Data + +Snowflake returns structured data: result sets, timestamps, aggregated counts, and event streams. Each shape maps to a different UI primitive, and picking the right one upfront saves substantial rework later. + +### Tables and Data Grids for Query Results + +For tabular query results, Reflex's table and data table components handle sorting, pagination, and column configuration natively. Warehouse query history, user activity logs, and cost attribution tables all fit this pattern cleanly. For time-series data like credit consumption or query latency, Recharts-based line and area charts give you full control over axes and formatting without leaving Python. + +| Component Type | Snowflake Data Type | Reflex Component | Use Case | +|---|---|---|---| +| Tabular data | Query result sets | rx.table, rx.data_table | Warehouse query history, user activity logs | +| Time-series metrics | TIMESTAMP, NUMBER | rx.recharts (line, area) | Credit consumption, query latency trends | +| Aggregated counts | COUNT, SUM | rx.stat, rx.card | Total queries, storage used, active users | +| Real-time streams | VARIANT (JSON) | rx.text, custom components | Live query feed, warehouse status | +| Filters | DATE, VARCHAR | rx.select, rx.date_picker | Filter by date range, warehouse, user role | + +### Computed Vars for Calculated Metrics + +Once Snowflake results load into Reflex state, computed vars take over. Cost per query, average execution time, storage growth rate: these all calculate automatically from the raw data in state, with no client-side JavaScript required. When upstream state changes, only the components that depend on those vars re-render. The result is a dashboard that stays current without manual DOM updates or polling logic. + +## Deploying Your Snowflake Dashboard to Production + +Once your dashboard is ready for production, you have two main paths: managed cloud hosting or self-hosted infrastructure. + +For most teams, managed deployment is the fastest route. The ``[reflex deploy command](https://reflex.dev/hosting/) handles the Python backend, Snowflake connector, compiled frontend, and infrastructure provisioning in one step. Reflex Cloud adds multi-region support, GitHub Actions and GitLab CI integration, and built-in monitoring without any extra configuration. + +### Enterprise and Compliance Deployments + +Finance, healthcare, and government have stricter requirements, and both Snowflake and Reflex account for that. Snowflake has expanded its Sovereign Cloud offerings to keep data within national borders for government and compliance-heavy industry clients. On the application side, finance, healthcare, and government teams can [deploy Reflex applications on-premises](https://reflex.dev/blog/on-premises-deployment/) using Helm charts for Kubernetes, keeping all code execution and Snowflake access entirely within their own infrastructure. + +This matters because data residency rules vary by region and industry. Running your dashboard inside your own network means query results from Snowflake never leave your environment, which satisfies most compliance requirements without extra tooling. + +The two options cover the full range of deployment needs: fast managed hosting for product and analytics teams, and self-hosted Kubernetes for organizations where infrastructure control is non-negotiable. + +## FAQ + +### Can I build a Snowflake dashboard without JavaScript? + +Yes. Reflex lets you build full Snowflake dashboards in pure Python, including queries, state management, and UI components, all in the same codebase. The Snowflake Connector for Python handles data access, while Reflex's 60+ built-in components cover charts, tables, and filters without requiring frontend development skills. + +### Snowflake dashboard Streamlit vs Reflex? + +Streamlit works for quick prototypes but breaks down with complex Snowflake workflows. Its rerun model causes memory leaks, and there's no event-based interaction or server push for real-time updates. Reflex handles full read-write workflows with Snowflake, supports production-grade authentication and deployment, and customers describe it as "Streamlit for adults" because you don't have to throw it away after prototyping. + +### How do I connect Snowflake to a Reflex dashboard? + +Install the Snowflake Connector for Python via pip, then configure your account identifier, warehouse, and database credentials at the project level in Reflex. Your Snowflake queries run directly in Reflex event handlers as Python code, with no middleware or API gateway required. The connection setup works the same way it would in any Python script. + +### What's the fastest way to deploy a Snowflake dashboard in 2026? + +Run `reflex deploy` for managed cloud hosting that handles your Python backend, Snowflake connector, and infrastructure in one command. For industries requiring data residency, deploy on-premises using Reflex's Helm charts for Kubernetes to keep all Snowflake query execution within your own network and satisfy compliance requirements. diff --git a/blog/how-to-build-python-web-app-with-bigquery.md b/blog/how-to-build-python-web-app-with-bigquery.md new file mode 100644 index 000000000..d573f5d8b --- /dev/null +++ b/blog/how-to-build-python-web-app-with-bigquery.md @@ -0,0 +1,127 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With BigQuery in 2026" +title_tag: "Build Python Web App With BigQuery April 2026" +description: "Learn how to build a Python web app with BigQuery in April 2026. Complete guide to creating production analytics dashboards using pure Python code." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "BigQuery Python app, BigQuery web app, data warehouse Python app, BigQuery integration, analytics Python app" + } +] +faq: [ + {"question": "Can I build a Python web app with BigQuery without learning JavaScript?", "answer": "Yes. Reflex handles both frontend and backend in pure Python, so you can build interactive BigQuery dashboards without writing any JavaScript. The entire stack—from query logic to UI components—lives in Python files that any data engineer can read and modify."}, + {"question": "What's the fastest way to connect BigQuery to a web app in 2026?", "answer": "Install the `google-cloud-bigquery` Python client library, configure your service account credentials as an environment variable, and call BigQuery directly from Reflex event handlers. Query results flow into state variables and the UI updates automatically when data returns."}, + {"question": "How do I deploy a BigQuery app to production?", "answer": "Run `reflex deploy` to automatically provision infrastructure and push your app live. Store BigQuery credentials as secrets through Reflex Cloud rather than hardcoding them, and use VPC or on-premises deployment options if you have compliance requirements that keep data within your security perimeter."}, + {"question": "BigQuery dashboard Streamlit vs Reflex?", "answer": "Streamlit's script rerun model causes memory leaks and performance issues under load, and you can't customize the UI beyond basic layouts. Reflex gives you full control over components, handles state updates without full reruns, and ships as a production-grade web app that teams can maintain long-term."}, + {"question": "What's the best framework for building a BigQuery analytics dashboard?", "answer": "Reflex works well if you need production-quality UI and want to stay in pure Python. It connects to BigQuery through standard Python client libraries, manages state updates automatically, and includes 60+ built-in components for data tables, charts, and filters without requiring frontend expertise."}, + {"question": "How does Reflex handle real-time updates when BigQuery returns new data?", "answer": "Reflex automatically re-renders only the affected UI components when BigQuery query results return and update state variables. Event handlers fire queries, results flow into state variables, and the UI responds without manual loading state management or fetch calls."}, + {"question": "What authentication methods work with BigQuery in a Reflex app?", "answer": "You can use service account JSON keys for production deployments, Application Default Credentials via Google Cloud SDK for local development, or OAuth 2.0 for user-specific data access. The BigQuery client picks up credentials automatically through the GOOGLE_APPLICATION_CREDENTIALS environment variable."}, + {"question": "Can I query BigQuery from a Reflex app without building a separate API layer?", "answer": "Yes. Because Reflex runs your backend as pure Python, you can call the google-cloud-bigquery client library directly from event handlers without building any API layer between your query logic and UI state."}, + {"question": "What types of BigQuery dashboards are finance teams building with Reflex?", "answer": "Finance teams use Reflex to build interactive analytics dashboards that query transaction data and surface trend lines for portfolio managers. The same pattern applies to real-time data visualization across portfolio monitoring, risk analytics, and financial reporting."}, + {"question": "How do I handle parameterized BigQuery queries in Reflex?", "answer": "Event handlers in your Reflex state class accept parameters from UI components like filters, date pickers, and dropdowns. These parameters feed directly into your BigQuery queries, and when results return, state variables update automatically without custom event wiring."}, + {"question": "Does Reflex support BigQuery for healthcare and government applications?", "answer": "Yes. Healthcare teams use Reflex with BigQuery to monitor patient volumes and operational metrics, while government teams analyze public datasets and visualize traffic patterns. Reflex supports VPC and on-premises deployment to meet compliance requirements in regulated industries."}, + {"question": "What built-in components does Reflex provide for BigQuery data visualization?", "answer": "Reflex ships with 60+ built-in components including data tables with sortable columns, charts for trend lines and aggregations, and filter controls like select menus, sliders, and date range pickers that wire directly to query parameters without custom event handling."}, + {"question": "How does the Reflex state model organize BigQuery query logic?", "answer": "A single Python state class holds your dataset rows, filter values, and loading flags. Event handler methods on that same class run BigQuery queries and update the state, keeping frontend and backend logic together in one readable file without separation between query logic and UI components."}, + {"question": "Can I keep my BigQuery credentials secure in a production Reflex deployment?", "answer": "Yes. Store your BigQuery service account credentials as secrets through Reflex Cloud rather than embedding them in code. For teams with strict compliance requirements, Reflex supports VPC and on-premises deployment so BigQuery connections never leave your security perimeter."}, + {"question": "What happens when a BigQuery query takes time to execute in a Reflex app?", "answer": "Reflex manages loading state automatically when event handlers fire BigQuery queries. The UI remains responsive, and only the components displaying query results re-render when data returns, without blocking other parts of the interface or requiring manual state management."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build production BigQuery analytics dashboards in pure Python without learning JavaScript + +- Reflex event handlers run parameterized BigQuery queries that update UI components automatically + +- The `google-cloud-bigquery` client library works directly in Reflex state classes with no API layer + +- Finance, healthcare, and government teams use this pattern for real-time data visualization at scale + +- Reflex is an open-source Python framework that lets you build full-stack web apps entirely in Python + +## Why Python Developers Are Building Web Apps With BigQuery in 2026 + +BigQuery has quietly become the default data warehouse for teams running analytics at scale. It handles petabyte queries in seconds, connects natively to Google Cloud Pub/Sub for real-time data streams, and offers Python client libraries that manage authentication and retries out of the box. For financial services teams, e-commerce analysts, and data engineers, that's a serious foundation. + +The problem is how that data gets surfaced. Most Python developers end up stuck in one of two places: [a Jupyter notebook](https://reflex.dev/blog/reflex-jupyter/) that only they can use, or a half-finished dashboard that required learning React just to make a button work. Neither is a real product. + +> + +"It's like Streamlit for adults. It's fast, it looks good, and we don't need to throw it away after prototyping." — Delta Global Head of Quant + +That's where 2026 looks different. Python developers are [building production web apps](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) directly on top of BigQuery, with Reflex handling the full stack in pure Python. No JavaScript, no separate frontend codebase, no glue layer between your query logic and your UI. BigQuery's APIs are built for backend engineers, and Reflex is built for exactly that kind of developer who wants a real web app without the frontend tax. + +## What You'll Build: A Python Web App Powered by BigQuery + +The app we're building is an interactive analytics dashboard that sits on top of a live BigQuery dataset. Users can filter by date range, segment by category, and view aggregated metrics through charts and tables, all without touching SQL. Behind the scenes, Reflex manages the state and updates the UI the moment a query returns. BigQuery does the heavy lifting on the data side. + +This pattern works across industries. In [finance](https://reflex.dev/use-cases/finance/), you're querying transaction data and surfacing trend lines for portfolio managers. In [healthcare](https://reflex.dev/use-cases/healthcare/), you're monitoring patient volumes or tracking performance metrics across facilities. [Government teams](https://reflex.dev/use-cases/government/) use this same setup to analyze public datasets and visualize traffic or resource patterns in real time. BigQuery [handles real-time data insights at scale](https://www.cloudoptimo.com/blog/navigating-bigquery-for-scalable-real-time-data-insights/), and Reflex gives that data a UI your whole organization can actually use. + +The core stack is straightforward. Reflex handles routing, state, and the component layer. BigQuery handles query execution. You write everything in Python, from the event handlers that fire when a user clicks a filter, to the chart components that render the response. + +## Connecting BigQuery to Your Reflex App + +The connection between BigQuery and Reflex starts with the `google-cloud-bigquery` Python client library. Install it via pip, set up your credentials, and you can call it from any Reflex event handler just like any other Python library. Because Reflex runs your backend as pure Python, there's no API layer to build between your query logic and your UI state. + +Authentication typically uses a service account JSON key file generated from Google Cloud Console. Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to that file path, and the BigQuery client picks it up automatically. For local development, Application Default Credentials via the Google Cloud SDK works fine. Production deployments should use a service account with secrets management. + +| Authentication Method | Configuration Location | Best For | Security Level | +|---|---|---|---| +| Service Account JSON | Environment variable or project config | Production deployments | High (with secrets management) | +| Application Default Credentials | Google Cloud SDK | Local development | Medium | +| OAuth 2.0 | OAuth flow in application | User-specific data access | High (per-user scoping) | + +Once credentials are in place, BigQuery queries live inside your Reflex state as event handlers. A user clicks a filter, the handler fires, the query runs, and results flow into state variables. Reflex updates the UI automatically. You never write a fetch call or manage loading state manually. Reflex also supports project-level integration configuration, so BigQuery credentials set once are shared across every app in that project with no duplication across environments. + +## Building the UI Around BigQuery in Pure Python + +Once your credentials are configured, the UI layer comes together quickly. State variables hold query results as Python lists or dataclasses, and event handlers fire parameterized BigQuery queries whenever users interact with filters, date pickers, or dropdowns. When results return, only the affected components re-render automatically. No fetch calls, no loading state juggling, no JavaScript. Following [dashboard design best practices](https://medium.com/@theeshreyarai/building-dashboards-on-bigquery-and-snowflake-a-complete-guide-540d175bd992) helps keep your BigQuery UI focused and performant. + +Reflex ships with 60+ built-in components that pair naturally with BigQuery output. For data-heavy apps, a few stand out: + +- Data tables for row-level query results with sortable columns, giving analysts a familiar spreadsheet-like view directly in the browser. + +- [Charts](https://reflex.dev/blog/top-10-data-visualization-libraries/) for aggregated metrics like trend lines and bar comparisons, wired directly to state variables that update on each query. + +- Select menus, sliders, and date range pickers as filter controls that feed directly into query parameters without any custom event wiring. + +The class-based state model keeps everything organized. One Python class holds your dataset rows, filter values, and loading flags. Event handler methods on that same class run the BigQuery queries, update the rows, and the UI responds. Frontend and backend logic live together in one file, readable by any Python developer on your team without frontend expertise. + +That readability pays off in production. When a query returns unexpected results, you open the state class and read exactly which parameters fed the query and what came back. No source maps, no compiled bundles. The same debugging workflow your data scientists already use for pandas and model code applies here directly. + +## Deploying Your BigQuery App to Production + +Running ``[reflex deploy](https://reflex.dev/hosting/) handles the heavy lifting of pushing your app live, provisioning infrastructure and managing scaling automatically. Store your BigQuery service account credentials as secrets through Reflex Cloud instead of embedding them in code, and use multi-region deployment to keep latency low for distributed teams. + +For finance, healthcare, or government teams with compliance requirements, Reflex supports VPC and [on-premises deployment](https://reflex.dev/blog/on-premises-deployment/) so your BigQuery connection never leaves your security perimeter. The quick-start deployment guide covers the full setup, and authentication configuration handles credential management across environments. + +## FAQ + +### Can I build a Python web app with BigQuery without learning JavaScript? + +Yes. Reflex handles both frontend and backend in pure Python, so you can build interactive BigQuery dashboards without writing any JavaScript. The entire stack, from query logic to UI components, lives in Python files that any data engineer can read and modify. + +### What's the fastest way to connect BigQuery to a web app in 2026? + +Install the `google-cloud-bigquery` Python client library, configure your service account credentials as an environment variable, and call BigQuery directly from Reflex event handlers. Query results flow into state variables and the UI updates automatically when data returns. + +### How do I deploy a BigQuery app to production? + +Run `reflex deploy` to automatically provision infrastructure and push your app live. Store BigQuery credentials as secrets through Reflex Cloud instead of hardcoding them, and use VPC or on-premises deployment options if you have compliance requirements that keep data within your security perimeter. + +### BigQuery dashboard Streamlit vs Reflex? + +Streamlit's script rerun model causes memory leaks and performance issues under load, and you can't customize the UI beyond basic layouts. Reflex gives you full control over components, handles state updates without full reruns, and ships as a production-grade web app that teams can maintain long-term. + +### What's the best framework for building a BigQuery analytics dashboard? + +Reflex works well if you need production-quality UI and want to stay in pure Python. It connects to BigQuery through standard Python client libraries, manages state updates automatically, and includes 60+ built-in components for data tables, charts, and filters without requiring frontend expertise. diff --git a/blog/how-to-build-python-web-app-with-dynamodb.md b/blog/how-to-build-python-web-app-with-dynamodb.md new file mode 100644 index 000000000..d53fd5140 --- /dev/null +++ b/blog/how-to-build-python-web-app-with-dynamodb.md @@ -0,0 +1,157 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With DynamoDB in 2026" +title_tag: "Build Python Web App With DynamoDB 2026" +description: "Learn how to build a Python web app with DynamoDB in April 2026. Write full-stack apps in pure Python without JavaScript using Reflex and boto3." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "DynamoDB Python app, DynamoDB web app, AWS DynamoDB Python, NoSQL Python app, DynamoDB integration, serverless database app" + } +] +faq: [ + {"question": "Can I build a Python web app with DynamoDB without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire app in Python, including both the DynamoDB backend logic and the UI that displays your data. You write boto3 queries and Reflex components in the same codebase, and the framework compiles everything into a production-ready web app automatically."}, + {"question": "How do I connect DynamoDB to a Reflex application?", "answer": "Import boto3 in your Reflex state class, initialize a DynamoDB resource in the `__init__` method, and store your table reference as an instance variable. Configure AWS credentials through environment variables or a credentials file, and call DynamoDB operations directly from event handlers—results flow into state variables and the UI updates automatically."}, + {"question": "What's the best way to query DynamoDB from a Python web interface?", "answer": "Use `query()` when you know the partition key, since it delivers predictable low latency and reads only the items you need. Reserve `scan()` for small tables or admin interfaces where you need every record. For most web apps, designing your partition and sort keys around common access patterns eliminates expensive scans entirely."}, + {"question": "When should I use DynamoDB instead of a traditional SQL database?", "answer": "DynamoDB makes sense when you need to handle unpredictable traffic spikes, scale beyond what a single database server can support, or avoid infrastructure management entirely. It handles over 10 trillion requests per day with single-digit millisecond latency, making it the right choice for user session stores, real-time inventory systems, or any application where serverless scaling matters more than complex relational queries."}, + {"question": "How do I deploy a Reflex app that uses DynamoDB to production?", "answer": "Run `reflex deploy` to ship both your FastAPI backend and compiled frontend as one application. Store AWS credentials as encrypted secrets in Reflex Cloud's secrets management system so boto3 handlers can access DynamoDB at runtime without exposing keys in your frontend code."}, + {"question": "How does Reflex handle real-time updates when DynamoDB data changes?", "answer": "When a Reflex event handler completes a DynamoDB operation and updates state variables, the UI re-renders automatically without requiring DOM manipulation or callbacks. For collaborative features where external writes occur, you can use DynamoDB Streams to capture item-level changes in near real-time and push UI updates to active sessions."}, + {"question": "What DynamoDB operations should I use for create and update workflows in Reflex?", "answer": "Use `put_item` for both create and update workflows, since it writes a new record or overwrites an existing one. For more granular updates that modify specific attributes conditionally, use `update_item` to change only the fields you need without replacing the entire item."}, + {"question": "Can I use Reflex's built-in components to display DynamoDB query results?", "answer": "Yes. Reflex ships with 60+ built-in components including data tables and AG Grid for advanced data interactions. The data table component maps each Python dictionary from your DynamoDB query results directly to rows, with item attributes automatically becoming columns."}, + {"question": "How do I handle AWS credentials securely in a Reflex DynamoDB app?", "answer": "Configure AWS credentials through environment variables or a standard AWS credentials file during development. In production, store them as encrypted secrets in Reflex Cloud's secrets management system where they're accessible to boto3 handlers at runtime but never exposed to the frontend code."}, + {"question": "What are partition keys and sort keys in DynamoDB and why do they matter?", "answer": "DynamoDB organizes data using partition keys and optional sort keys, which determine what query patterns are possible without expensive full table scans. Design your keys around your most common access patterns before building your app, since the key schema directly impacts query performance and cost."}, + {"question": "Does Reflex require a separate frontend repository when building DynamoDB apps?", "answer": "No. With Reflex, your entire app lives in Python without requiring a separate frontend repository or JavaScript codebase. You query DynamoDB using boto3 in the same files where you define UI components, and Reflex compiles everything into a FastAPI backend and React frontend automatically."}, + {"question": "How do I filter DynamoDB query results based on user input in Reflex?", "answer": "Capture user input through Reflex form components, then pass those values to event handlers that call DynamoDB's `query()` operation with key conditions based on the input. When the handler updates state with filtered results, the UI components bound to that state re-render automatically with the filtered subset."}, + {"question": "What makes DynamoDB suitable for applications with unpredictable traffic patterns?", "answer": "DynamoDB is serverless and handles over 10 trillion requests per day with peaks exceeding 20 million requests per second, all with zero infrastructure management. It automatically scales to handle traffic spikes without capacity planning, making it ideal for applications where user load is unpredictable or seasonal."}, + {"question": "Can I deploy a Reflex DynamoDB app to meet data sovereignty and compliance requirements?", "answer": "Yes. Reflex supports VPC deployment and on-premises hosting that keeps both application and DynamoDB traffic inside private networks, satisfying data sovereignty requirements for regulated workloads. DynamoDB also offers point-in-time recovery with continuous backups for up to 35 days to meet audit logging obligations."}, + {"question": "How do DynamoDB global tables work with Reflex for multi-region deployments?", "answer": "DynamoDB global tables provide multi-region deployment with up to 99.999% availability, allowing reads and writes from any region with strong consistency. This pairs naturally with Reflex Cloud's multi-region deployment capabilities, keeping both your application layer and database layer geographically close to users worldwide."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- DynamoDB handles 10+ trillion requests daily with zero server management or capacity planning + +- Reflex lets you build DynamoDB-backed web apps entirely in Python without writing JavaScript + +- Your state class calls boto3 operations directly and UI components update automatically when data changes + +- Deploy with `reflex deploy` and store AWS credentials as encrypted secrets that never touch the frontend + +- Reflex is a full-stack Python framework that builds production web apps without requiring frontend expertise + +## Why Python Developers Are Building Web Apps With DynamoDB in 2026 + +Managing data at scale used to mean hiring a DBA, provisioning servers, and spending weeks on capacity planning. DynamoDB cuts all of that out. It's a serverless, fully managed NoSQL database that delivers single-digit millisecond performance at any scale with zero infrastructure management. No clusters to provision, no maintenance windows to schedule. + +That's why Python developers keep reaching for it in 2026. When you're building apps that need to support millions of concurrent users, like user-content metadata stores or high-concurrency caches, DynamoDB handles the load without you thinking about it. Pair it with Python's boto3 library and you get a genuinely powerful toolkit for building serverless, scalable applications fast. + +The missing piece, historically, was the frontend. Python developers comfortable with boto3 and DynamoDB still had to learn React or wire up a separate JavaScript codebase just to display their data. That's where [Reflex, a pure Python web framework](https://reflex.dev/blog/top-python-web-frameworks/), closes the gap. + +With Reflex, your entire [app lives in Python](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/). You query DynamoDB in the same language you already know, and the UI reacts automatically when your data changes. No JavaScript, no separate frontend repo, no context-switching between two different worlds. Just Python, end to end, from database read to displayed component. + +## What You'll Build: A Python Web App Powered by DynamoDB + +By the end of this guide, you'll have a working [data management interface](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/) that queries DynamoDB tables, displays results in real-time, and lets users create, update, and delete records through a clean UI. All of it written in Python. + +The app will display DynamoDB items in a data table, support filtering and pagination, and include forms for record creation and updates. [Reflex compiles your Python](https://reflex.dev/blog/reflex-architecture/) into a FastAPI backend and React frontend automatically, so you get a production-grade app without writing a line of JavaScript. + +Why does DynamoDB make sense here? It handles [more than 10 trillion requests](https://aws.amazon.com/dynamodb/) per day and supports peaks of more than 20 million requests per second. That kind of throughput matters whether you're building user session management, inventory tracking, or anything else where unexpected traffic spikes are a real concern. + +The pattern you'll learn applies across a wide range of real use cases: + +| Application Pattern | DynamoDB Use Case | UI Components Needed | +|---|---|---| +| User Session Manager | Store and retrieve session data with TTL | Data grid, authentication forms, session details panel | +| Inventory Tracker | Real-time product stock levels with updates | Product table, update forms, search filters | +| Analytics Dashboard | Query metrics with secondary indexes | Charts, data tables, date range selectors | +| Content Management | Store flexible document structures | Rich text editor, media upload, preview pane | + +Reflex ships with 60+ built-in components, so everything in that last column is already available to you out of the box, along with [ready-to-use templates](https://reflex.dev/templates/) for common patterns. + +## Connecting DynamoDB to Your Reflex App + +boto3 is the standard Python SDK for AWS, and it's how you'll talk to DynamoDB from your Reflex app. It offers two interfaces: a low-level client that maps closely to the DynamoDB API, and a higher-level resource interface that exposes tables as Python objects with a more readable API. For most Reflex apps, the resource interface is the better starting point. + +Since Reflex has no official DynamoDB integration, you're working with boto3 directly, which is perfectly fine. Any Python library can be imported and called from Reflex event handlers. Configure your AWS credentials through environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`) or a standard AWS credentials file. Because Reflex integrations are configured at the project level, those credentials become available across every handler in your app automatically. + +### Setting Up State + +Your Reflex state class is where the DynamoDB connection lives. Import boto3, initialize a DynamoDB resource inside the state's `__init__` method, and store your table reference as an instance variable. From there, event handlers call DynamoDB operations directly. + +The four operations you'll use most often: + +- `put_item` writes a new record or overwrites an existing one, making it useful for both create and update workflows. + +- `get_item` retrieves a single item by its partition key with predictable, low latency. + +- `query` fetches multiple items sharing a partition key, optionally filtered by sort key conditions. + +- `scan` reads all items in a table, which works fine for small datasets but becomes expensive at scale. + +Each response flows into a state variable, and Reflex's reactive system handles the rest. When a state variable changes, every UI component bound to it updates automatically. + +### Keys and Capacity + +DynamoDB organizes data using partition keys and optional sort keys. Getting your key schema right matters before you write a single line of app code, since it determines what query patterns are possible without a full scan. DynamoDB charges based on read and write capacity units, so scans on large tables can get costly fast. Design your keys around your most common access patterns, and use secondary indexes when you need to query on non-key attributes. + +## Building the UI Around DynamoDB in Pure Python + +Reflex's state management connects directly to DynamoDB operations without any middleware layer. Your state class holds the DynamoDB table reference and query results as typed state variables. Event handlers call boto3 operations directly: `scan()` loads all items into a state list, `query()` filters by key conditions based on form input, and `put_item()` writes new records from submissions. Because the table resource returns native Python types automatically, those results slot straight into component props without any transformation. + +### Displaying DynamoDB Data in Components + +[Reflex's data table component](https://reflex.dev/blog/using-table-component/) maps each Python dictionary in your state list to a row, with item attributes becoming columns. Form components capture user input and pass values directly to write handlers, or you can use [AG Grid for advanced data interactions](https://reflex.dev/blog/using-ag-grid-in-reflex/). When a handler completes a DynamoDB operation and updates state, the UI refreshes automatically with no DOM manipulation and no callbacks required. + +| DynamoDB Operation | Reflex Event Handler Pattern | UI Component Update | +|---|---|---| +| `scan()` | Loads all items into state list | Data table shows full list | +| `query()` | Filters by partition/sort key | Data table shows filtered subset | +| `get_item()` | Retrieves single item by key | Detail panel displays attributes | +| `put_item()` | Creates new item from form data | Table updates with new row | +| `update_item()` | Modifies attributes conditionally | Row updates with new values | +| `delete_item()` | Removes item by key | Row disappears from table | + +For collaborative features, [DynamoDB Streams](https://aws.amazon.com/dynamodb/features/) capture item-level changes in near real-time as a time-ordered sequence, with each record appearing exactly once, letting your app consume external writes and push UI updates to active sessions. + +## Deploying Your DynamoDB App to Production + +Deploying a Reflex app backed by DynamoDB follows a single-command workflow. Running `reflex deploy` provisions infrastructure and ships both the FastAPI backend and compiled React frontend as a unified application. Your AWS credentials never touch the frontend. Store them as encrypted secrets in Reflex Cloud's secrets management system, where they're accessible to your boto3 handlers at runtime and nowhere else. + +For global reach, [DynamoDB global tables](https://aws.amazon.com/dynamodb/) give you multi-region deployment with up to 99.999% availability and strong consistency, supporting zero RPO applications that read and write from any region. That pairs naturally with Reflex Cloud's multi-region deployment, so both your app layer and database layer stay geographically close to your users. + +### Production Readiness for Data Applications + +Reflex Cloud's built-in metrics surface application performance data alongside your DynamoDB capacity consumption, giving you one place to watch for throttling or latency spikes. On the data side, [point-in-time recovery](https://aws.amazon.com/dynamodb/features/) protects tables from accidental writes or deletes with continuous backups and per-second recovery granularity for up to 35 days. + +For compliance-focused workloads covering financial records, healthcare data, or user profiles, [Reflex supports VPC deployment](https://reflex.dev/blog/reflex-streamlit/) and on-premises hosting that keeps both the application and DynamoDB traffic inside private networks. That architecture satisfies data sovereignty requirements and audit logging obligations without changing how you write the app itself. + +## FAQ + +### Can I build a Python web app with DynamoDB without learning JavaScript? + +Yes. Reflex lets you build the entire app in Python, including both the DynamoDB backend logic and the UI that displays your data. You write boto3 queries and Reflex components in the same codebase, and the framework compiles everything into a production-ready web app automatically. + +### How do I connect DynamoDB to a Reflex application? + +Import boto3 in your Reflex state class, initialize a DynamoDB resource in the `__init__` method, and store your table reference as an instance variable. Configure AWS credentials through environment variables or a credentials file, and call DynamoDB operations directly from event handlers: results flow into state variables and the UI updates automatically. + +### What's the best way to query DynamoDB from a Python web interface? + +Use `query()` when you know the partition key, since it delivers predictable low latency and reads only the items you need. Reserve `scan()` for small tables or admin interfaces where you need every record. For most web apps, designing your partition and sort keys around common access patterns eliminates expensive scans entirely. + +### When should I use DynamoDB instead of a traditional SQL database? + +DynamoDB makes sense when you need to handle unpredictable traffic spikes, scale beyond what a single database server can support, or avoid infrastructure management entirely. It handles over 10 trillion requests per day with single-digit millisecond latency, making it the right choice for user session stores, real-time inventory systems, or any application where serverless scaling matters more than complex relational queries. + +### How do I deploy a Reflex app that uses DynamoDB to production? + +Run `reflex deploy` to ship both your FastAPI backend and compiled frontend as one application. Store AWS credentials as encrypted secrets in Reflex Cloud's secrets management system so boto3 handlers can access DynamoDB at runtime without exposing keys in your frontend code. diff --git a/blog/how-to-build-python-web-app-with-gcp.md b/blog/how-to-build-python-web-app-with-gcp.md new file mode 100644 index 000000000..fc1c4d8c8 --- /dev/null +++ b/blog/how-to-build-python-web-app-with-gcp.md @@ -0,0 +1,146 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With GCP in 2026" +title_tag: "Build Python Web Apps With GCP (April 2026)" +description: "Learn how to build a Python web app with GCP in April 2026. Connect Vertex AI, Cloud SQL, and Cloud Run in pure Python without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "GCP Python app, Google Cloud web app, GCP integration Python, Vertex AI Python app, Cloud Storage Python app" + } +] +faq: [ + {"question": "Can I build a Python web app with GCP without learning JavaScript?", "answer": "Yes. Reflex lets you build full-stack web applications in pure Python, connecting GCP services like Vertex AI and Cloud SQL directly to interactive UIs without writing any JavaScript or managing a React build pipeline."}, + {"question": "What's the fastest way to deploy a Python app to GCP in 2026?", "answer": "Write your app in Reflex using GCP client libraries for services like Vertex AI and Cloud SQL, then deploy to Cloud Run with automatic scaling. Your entire stack stays in Python, from database queries to frontend UI, and Cloud Run handles infrastructure without manual server management."}, + {"question": "How do I stream Gemini 3.1 Pro responses to users in real time?", "answer": "Reflex's event system lets you iterate over Vertex AI's streaming response and yield each token back to the browser immediately over WebSocket. Users see responses appear token by token without polling or client-side JavaScript, all controlled from Python event handlers."}, + {"question": "What GCP services work with Reflex?", "answer": "All of them. Since Reflex's backend runs standard Python, any GCP client library works inside event handlers exactly as it would in a script—Vertex AI for LLMs, Cloud SQL for databases, Cloud Storage for files, and Cloud Run for deployment all integrate through their official Python SDKs."}, + {"question": "How do I handle GCP credentials in production Reflex apps?", "answer": "Set your service account JSON and API keys as environment variables through your hosting dashboard before deploying. Your state class reads them at runtime via Python's standard environment variable access, and credentials never touch your codebase or version control."}, + {"question": "Does Reflex require a separate frontend and backend codebase like traditional web frameworks?", "answer": "No. Reflex lets you write both frontend UI components and backend logic in a single Python codebase. Components automatically render state variables, and event handlers update state directly, eliminating the need for separate JavaScript frontend code or REST APIs between layers."}, + {"question": "Can I use Cloud SQL with Reflex for database operations?", "answer": "Yes. Cloud SQL integrates through standard Python database adapters and the google-cloud-sql-connector package. Query results stored in state variables automatically update UI components like data tables, with loading states and error handling controlled through the same state class."}, + {"question": "What Python version do I need to run Reflex with GCP services?", "answer": "Reflex requires Python 3.10 or higher, which already falls within the supported range for all current GCP Python client libraries. This ensures full compatibility with services like Vertex AI, Cloud SQL, and Cloud Storage without version conflicts."}, + {"question": "How does authentication work for GCP-powered Reflex apps?", "answer": "For local development, use `gcloud auth application-default login` for automatic credential pickup. In production, store service account JSON as environment variables that your state class reads at runtime, keeping secrets out of version control while maintaining the same code across environments."}, + {"question": "Can I add Google Auth login to my Reflex app?", "answer": "Yes. The blog demonstrates a dashboard example that uses Google Auth to restrict access to authenticated users only. Reflex supports authentication flows that integrate with Google's identity services while keeping all logic in Python."}, + {"question": "What happens when a user submits a form that calls Vertex AI in a Reflex app?", "answer": "An event handler fires when the form submits, calls the Gemini model through the Vertex AI Python SDK, and updates state variables with the response. Reflex automatically pushes these state changes to the UI over WebSocket, updating components without page reloads or manual DOM manipulation."}, + {"question": "Can I deploy Reflex apps with GCP connectivity to on-premises infrastructure?", "answer": "Yes. Reflex apps can deploy on-premises or inside a VPC while maintaining full GCP connectivity to services like BigQuery, Vertex AI, and Cloud Storage. The deployment pattern stays consistent whether you're running in the cloud or in regulated environments like healthcare or finance."}, + {"question": "How do I monitor costs when using Vertex AI in a Reflex application?", "answer": "Set budget alerts in the GCP Console for Vertex AI API spend to track usage costs. Your hosting environment surfaces application logs and error rates, while GCP shows quota consumption and authentication failures, giving you complementary monitoring across both infrastructure layers."}, + {"question": "Do I need to write REST APIs to connect my Reflex frontend to GCP services?", "answer": "No. GCP client libraries run directly inside Reflex event handlers as standard Python code. There's no middleware, REST wrapper, or separate API layer required—Vertex AI calls, Cloud SQL queries, and Cloud Storage operations happen in the same backend methods that update your UI state."}, + {"question": "What advantages does Cloud Run provide for Reflex deployments?", "answer": "Cloud Run handles autoscaling automatically and provides an HTTPS endpoint without manual server management. It becomes your deployment target where the same Python codebase that queries GCP services locally runs in production with automatic scaling based on traffic demand."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build full-stack web apps with GCP services in pure Python using Reflex + +- Connect Vertex AI, Cloud SQL, and Cloud Run directly through Python event handlers + +- Deploy to Cloud Run with automatic scaling while maintaining a single Python codebase + +- Reflex is an open-source framework that lets you build production web apps without JavaScript + +## Why Python Developers Are Building Web Apps With GCP in 2026 + +GCP has quietly become the go-to cloud for Python developers who want serious infrastructure without the ops overhead. Cloud Run handles autoscaling automatically, Vertex AI surfaces frontier LLMs like Gemini 3.1 Pro through clean Python SDKs, and Cloud SQL connects to your data layer without spinning up servers manually. The entire stack is accessible from Python. The missing piece, historically, has always been the frontend. + +Most Python developers hit the same wall: they can query Vertex AI, process data with Cloud SQL, and ship a Cloud Run container in an afternoon. But wrapping all of that in a production-grade UI means writing JavaScript, managing a React build pipeline, and maintaining two separate codebases. For data scientists and backend engineers, that's a real blocker. + +That's exactly where Reflex fits. [Reflex builds full-stack apps in Python](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/), connecting GCP services directly to interactive UIs without a separate frontend layer. Cloud Run becomes your deployment target. Vertex AI becomes a Python function call your UI can react to. Cloud SQL becomes a database your app reads from and writes to, all within the same Python codebase your team already understands. + +In 2026, this combination means you can go from idea to production without hiring a frontend engineer or learning a new language. + +## What You'll Build: A Python Web App Powered by GCP + +The app we're building is a data dashboard that queries Vertex AI's Gemini 3.1 Pro model for LLM-powered responses, reads from Cloud SQL for structured data, and deploys to Cloud Run for automatic scaling behind an HTTPS endpoint. Users log in with Google Auth, submit form inputs that trigger backend processing, and see results update in real time without any page reloads. + +Here's what the finished app includes: + +- A login screen backed by [Google Auth](https://reflex.dev/blog/implementing-sign-in-with-google/), so only authenticated users can access the dashboard + +- A form that accepts user input and sends it to Vertex AI, streaming the response back into the UI + +- A data table pulling live records from Cloud SQL, [refreshing on demand](https://reflex.dev/hosting/) + +- Cloud Run handling all deployment and scaling automatically, with no server management required + +The entire thing is written in Python. No JavaScript, no React, no separate build pipeline. + +The key idea here is that your GCP services stop being backend infrastructure and become Python function calls your UI responds to directly. When users submit a form, [an event handler fires](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/), calls Gemini 3.1 Pro, and updates the displayed state. That's the whole flow. + +## Connecting GCP to Your Reflex App + +Connecting GCP to a Reflex app is straightforward because Reflex's backend runs standard Python. There is no special integration layer or abstraction to work around. Any GCP client library you would use in a script works inside a Reflex event handler exactly the same way. + +### Setting Up GCP Authentication + +For local development, application default credentials work cleanly: run `gcloud auth application-default login` and the GCP client libraries pick up credentials automatically. For production, service account JSON is the more reliable path. Store the JSON key as an environment variable and reference it in your Reflex state class just as you would in any Python backend. When deploying to [Reflex Cloud](https://reflex.dev/blog/self-hosting-reflex-with-docker/), set environment variables through the dashboard or CLI so credentials never touch your codebase. + +### Installing GCP Python Client Libraries + +GCP's Python client libraries are compatible with all current active and maintenance Python versions. Since Reflex requires Python 3.10+, you are already in a supported range. Install what you need via pip and add them to your requirements.txt so Reflex Cloud picks them up automatically on deployment. + +| GCP Service | Python Package | Primary Use Case | +|---|---|---| +| Cloud Run | google-cloud-run | Deployment management | +| Vertex AI | google-cloud-aiplatform | LLM integration and ML models | +| Cloud SQL | google-cloud-sql-connector | Database connectivity | +| Cloud Storage | google-cloud-storage | File and object storage | + +Once installed, calling these libraries happens directly inside event handlers. A Vertex AI call to Gemini 3.1 Pro sits inside a backend method on your state class. When it returns, you assign the result to a state variable and Reflex pushes the update to the UI automatically. Cloud SQL connections follow the same pattern using standard Python database adapters. The [Vertex AI SDK for Python](https://docs.cloud.google.com/vertex-ai/docs/python-sdk/use-vertex-ai-python-sdk) provides straightforward methods for model interaction without middleware, REST wrappers, or glue code. + +## Building the UI Around GCP in Pure Python + +[Reflex components](https://reflex.dev/blog/custom-components/) display whatever lives in your state variables. That connection is what makes GCP integration feel natural: query Cloud SQL, store the results in a state var, and a data table updates automatically. Call Vertex AI from a button click, and the response flows directly into the component that displays it. The Python developer who knows the GCP SDK owns the whole application without touching a JavaScript file. + +### Displaying Cloud SQL Query Results + +When a user triggers a data refresh, the event handler runs your Cloud SQL query, maps the returned rows to a list on the state class, and Reflex handles the rest. While the query runs, a loading boolean on state controls a spinner component. If the connection fails, an error string var drives a dismissible alert component. The pattern stays consistent: state holds the data, components read from state, and event handlers change state. No manual DOM updates, no async callback trees. + +### Streaming Vertex AI Responses to the UI + +Streaming is where the Reflex architecture earns its keep. When you call Gemini 3.1 Pro via the Vertex AI SDK and iterate over the response stream, each token can be appended to a state string and yielded back to the browser immediately. Reflex's special event system pushes each yield to the frontend over WebSocket, so users see responses appear token by token the same way they would in a dedicated chat product. No polling, no client-side JavaScript to write, and no separate streaming endpoint to configure. + +The result is a chat interface where the user submits a prompt, your event handler streams Claude Opus 4.6 or Gemini 3.1 Pro back through yield statements, and a text component updates live. The developer who wrote the Vertex AI query also owns the UI that displays it. + +## Deploying Your GCP App to Production + +Once your app is working locally, getting it to production involves a few focused steps. GCP service connections travel with the app through environment variables instead of hardcoded config, so the same event handlers that ran locally continue calling Vertex AI and Cloud SQL without modification after deployment. For teams deploying directly to GCP infrastructure, [Cloud Run's Python deployment guide](https://docs.cloud.google.com/run/docs/quickstarts/build-and-deploy/deploy-python-service) covers containerization and scaling configuration. + +### Managing GCP Credentials in Production + +Set your service account JSON and API keys as environment variables through your hosting dashboard or CLI before deploying. Your state class reads them at runtime via standard Python environment variable access. When credentials rotate, update the variable and redeploy. No code changes, no secrets committed to version control. + +For teams in compliance-sensitive industries like finance, healthcare, or government, the same application can [deploy on-premises or inside a VPC](https://reflex.dev/blog/on-premises-deployment/) while maintaining full GCP connectivity. Whether you're connecting to BigQuery, Vertex AI, or Cloud Storage, the deployment pattern stays consistent across environments. + +### Monitoring GCP API Usage + +Built-in observability layers surface application logs directly in your hosting environment. GCP-side quota consumption and authentication failures appear in your GCP Console alongside project metrics. Set budget alerts in GCP for Vertex AI API spend and configure hosting-level alerts for error rate spikes. The two monitoring surfaces complement each other: your app host shows you what the app did, GCP shows you what it cost. + +## FAQ + +### Can I build a Python web app with GCP without learning JavaScript? + +Yes. Reflex lets you build full-stack web applications in pure Python, connecting GCP services like Vertex AI and Cloud SQL directly to interactive UIs without writing any JavaScript or managing a React build pipeline. + +### What's the fastest way to deploy a Python app to GCP in 2026? + +Write your app in Reflex using GCP client libraries for services like Vertex AI and Cloud SQL, then deploy to Cloud Run with automatic scaling. Your entire stack stays in Python, from database queries to frontend UI, and Cloud Run handles infrastructure without manual server management. + +### How do I stream Gemini 3.1 Pro responses to users in real time? + +Reflex's event system lets you iterate over Vertex AI's streaming response and yield each token back to the browser immediately over WebSocket. Users see responses appear token by token without polling or client-side JavaScript, all controlled from Python event handlers. + +### What GCP services work with Reflex? + +All of them. Since Reflex's backend runs standard Python, any GCP client library works inside event handlers exactly as it would in a script: Vertex AI for LLMs, Cloud SQL for databases, Cloud Storage for files, and Cloud Run for deployment all integrate through their official Python SDKs. + +### How do I handle GCP credentials in production Reflex apps? + +Set your service account JSON and API keys as environment variables through your hosting dashboard before deploying. Your state class reads them at runtime via Python's standard environment variable access, and credentials never touch your codebase or version control. diff --git a/blog/how-to-build-python-web-app-with-jira.md b/blog/how-to-build-python-web-app-with-jira.md new file mode 100644 index 000000000..0602165e5 --- /dev/null +++ b/blog/how-to-build-python-web-app-with-jira.md @@ -0,0 +1,147 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Jira in 2026" +title_tag: "Build Python Web App With Jira (2026)" +description: "Learn how to build a Python web app with Jira REST API in April 2026. Create custom dashboards, JQL filters, and status workflows without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Jira Python app, Jira API web app, project tracking Python, Jira integration, issue management Python app" + } +] +faq: [ + {"question": "Can I build a Jira web app without JavaScript?", "answer": "Yes. Reflex lets you build full Jira integrations in pure Python, writing both the frontend UI and backend API logic without touching JavaScript. The `jira` or `atlassian-python-api` SDK handles data fetching, while Reflex components render tables, forms, and dashboards entirely in Python code."}, + {"question": "How to build a Python web app with Jira in 2026?", "answer": "Connect the Jira Python SDK to a Reflex state class, store credentials in environment variables, and use event handlers to fetch issues via JQL queries. Render results with `rx.data_table` and `rx.card` components, then deploy with `reflex deploy` — no separate frontend build required."}, + {"question": "What's the difference between Reflex and Streamlit for Jira dashboards?", "answer": "Reflex uses event-based state updates that propagate changes instantly across the UI, while Streamlit's script rerun model re-executes your entire application on every interaction. For Jira apps with status transitions, assignee updates, or multi-step workflows, Reflex handles real-time state changes without memory leaks or full-page refreshes."}, + {"question": "When should I deploy my Jira app on-premises vs Reflex Cloud?", "answer": "Deploy on-premises or in a VPC if your organization has compliance requirements around Jira data access or needs to keep credentials within your security perimeter. Reflex Cloud with multi-region deployment works well for teams without those constraints, offering the same development experience with faster setup."}, + {"question": "How do Reflex computed vars work with Jira data?", "answer": "Computed vars automatically derive metrics like open issue counts or sprint burndown totals from your Jira state variables, recalculating whenever the underlying data changes. Define them as properties on your state class using `@rx.var`, and they update reactively without manual refresh logic."}, + {"question": "Can I update Jira issue status directly from a Reflex app?", "answer": "Yes. Event handlers in Reflex can call the Jira SDK's transition methods to update issue status, then immediately update state variables to reflect the change in the UI without requiring a page refresh."}, + {"question": "What Jira API credentials do I need for a Reflex integration?", "answer": "You need your Jira instance URL, email address, and an API token. These credentials are stored in environment variables during development and in Reflex Cloud's secure credential storage for production deployments."}, + {"question": "How does rx.data_table render Jira issues in a Reflex app?", "answer": "You bind rx.data_table directly to a state variable containing your issue list from a JQL query. The table automatically re-renders whenever that state variable changes, displaying sortable and filterable Jira data without manual refresh logic."}, + {"question": "Can I filter Jira issues by custom fields in a Reflex dashboard?", "answer": "Yes. After fetching issues via the Jira SDK, you can filter state variables by any field including custom fields before rendering. This enables team-specific views that combine issues across multiple projects with custom filtering logic written in Python."}, + {"question": "Does Reflex support both Jira Cloud and Jira Data Center?", "answer": "Yes. Both the jira and atlassian-python-api SDKs work with Jira Cloud and Data Center instances. You configure your instance URL and credentials once, and the same Reflex app code works across both deployment types."}, + {"question": "How do I create new Jira issues from a Reflex form?", "answer": "Build a form using rx.input and rx.select components tied to state variables, then create an event handler that calls the Jira SDK's issue creation method with the form data. The handler updates state immediately after the API call succeeds."}, + {"question": "What happens when multiple users update the same Jira issue in a Reflex app?", "answer": "Each user's event handler makes independent API calls to Jira and updates their local state. Reflex's reactive state system ensures each user sees their own changes immediately, though you'll need to implement polling or webhooks for real-time synchronization across users."}, + {"question": "Can I run JQL queries with multiple filters in a Reflex Jira app?", "answer": "Yes. Store preset JQL queries in state variables or let users build queries dynamically through UI controls. Event handlers execute the JQL via the SDK's search method and populate the issue list state variable with results."}, + {"question": "How do I display Jira sprint data in a Reflex dashboard?", "answer": "Use the Jira SDK to fetch sprint issues, then render them with rx.grid or rx.stack components grouped by status or assignee. Computed vars can derive metrics like burndown totals that automatically recalculate when sprint data changes."}, + {"question": "What's the deployment process for a Reflex Jira app with sensitive data?", "answer": "For compliance requirements, deploy on-premises or in a VPC using Reflex's self-hosting option to keep Jira credentials within your security perimeter. For standard deployments, use reflex deploy with credentials stored in Reflex Cloud's project-level secure storage."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You build Jira web apps in pure Python without React or Vue using Reflex's full-stack framework + +- Pull data via Jira's REST API, render it in `rx.data_table`, and update issues through event handlers + +- Deploy with `reflex deploy` and store credentials in secure project-level config shared across apps + +- Reflex lets you write custom dashboards, JQL filters, and status workflows in Python with automatic UI updates + +## Why Python Developers Are Building Web Apps With Jira in 2026 + +Jira's built-in interface handles the general case well. It falls apart the moment your team's workflow gets specific. Sprint dashboards that combine data from five projects, custom triage views filtered by component and assignee, automated ticket escalation tools with business logic baked in - none of that ships out of the box. Teams end up stitching together JQL queries, Confluence macros, and spreadsheet exports just to see what they actually need to see. + +For Python developers, the traditional fix was painful. You'd pull data from the [Jira REST API](https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/) using the `jira` or `atlassian-python-api` library, write the business logic in Python, and then face a wall: building the frontend required React or Vue. That's a context switch most data engineers and backend developers don't want to make. + +That gap is exactly what Reflex closes. You write your Jira integration logic in Python, your UI components in Python, and your state management in Python. There's no JavaScript, no bundler configuration, no frontend/backend handoff. + +In 2026, Python developers aren't scripting against Jira anymore. They're shipping production web apps on top of it. + +## What You'll Build: A Python Web App Powered by Jira + +The app you're building is a custom Jira issue dashboard with features Jira's native interface won't give you. Picture a filtered issue table that runs JQL queries on demand, a status update panel that writes changes back to Jira in real time, and team-specific views that combine issues across multiple projects into a single unified layout. + +Here's the core interaction loop: + +- A user enters or selects a JQL query from a preset menu, giving teams quick access to the issue slices they actually care about + +- The app fetches matching issues from the Jira REST API and displays them in a sortable, filterable table built entirely in Python + +- Users update issue status or assignee directly in the UI, and the app patches the change via the API without leaving the page + +- State updates propagate instantly across the interface, no page refresh required + +The result is a production-ready web app, not a script output or a throwaway prototype. Reflex handles state management, routing, and UI generation in pure Python, so you ship something you'd genuinely put in front of a stakeholder. + +If you want a head start, check out the [Reflex template gallery](https://reflex.dev/templates/) for dashboard layouts you can adapt. Or skip straight to [build.reflex.dev](https://build.reflex.dev/) and describe your Jira app in plain English to generate a working scaffold in seconds. + +## Connecting Jira to Your Reflex App + +Reflex's backend runs pure Python, which means any Python SDK drops in without friction. The architectural pattern here is straightforward: credentials live in environment variables or secrets management, the Jira client initializes inside your state class, and data flows from event handlers into reactive state variables that the UI reads automatically. + +### Authentication and SDK Setup + +Start by installing your preferred Jira SDK via pip. Either `jira` or `atlassian-python-api` both work well. Once installed, pull your Jira credentials (your instance URL, email, and API token) from environment variables inside your Reflex state class. You set credentials once per workspace and every app in that project inherits them automatically. This works for both Jira Cloud and Data Center instances. For a detailed comparison of [Jira Python integration methods](https://airbyte.com/data-engineering-resources/jira-python-integration), including API calls versus data syncing approaches, external resources can help you choose the right pattern for your use case. + +### State Architecture for Jira Data + +State variables hold everything: issue lists, project metadata, sprint data, whatever your JQL returns. Event handlers call the SDK, parse the response, and assign results to those state variables. From there, Reflex's reactive state system does the rest. When state updates, every UI component that references those variables updates automatically with no manual refresh or polling loop required. + +If you want to go deeper on computed vars and [background event handlers](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/), the full state reference is available in the Reflex docs. + +## Building the UI Around Jira in Pure Python + +Reflex's component library covers everything you need to render Jira data, including tables, cards, badges, selects, and grids, all written in Python. The same developer who understands the Jira SDK builds the complete frontend with no handoffs and no context switching. + +### Displaying Issue Lists and Details + +``[rx.data_table](https://reflex.dev/blog/using-table-component/) is your starting point for JQL results. Bind it directly to a state variable holding your issue list, and the table updates automatically whenever that variable changes. For detail views, `rx.card` and `rx.badge` handle status indicators and priority labels cleanly. Click handlers on table rows update a `current_issue` state variable, swapping the view from list to detail without any custom routing logic. + +### Interactive Issue Management + +Forms for creating or updating issues use `rx.input` and `rx.select` components tied to state variables. Status transitions work through dropdown menus or buttons that call event handlers, which patch the change via the SDK and update state immediately. + +### Custom Dashboards and Filtering + +For team-specific views, filter state variables by assignee, sprint, or custom field before display. Aggregate metrics like open issue counts and burndown totals become computed vars. + +| Jira Data Type | Reflex Component | State Variable Type | Event Handler Pattern | +|---|---|---|---| +| Issue List | rx.data_table | List[Dict] | jql_search() updates issues state | +| Issue Detail | rx.card, rx.badge | Dict | get_issue() populates current_issue | +| Status Transition | rx.select, rx.button | String | transition_issue() calls SDK method | +| Custom Field | rx.input, rx.text_area | String or List | update_field() modifies issue data | +| Sprint Board | rx.grid, rx.stack | List[Dict] grouped | get_sprint_issues() filters by sprint | + +## Deploying Your Jira App to Production + +When your app is ready, a single ``[reflex deploy pushes to Reflex Cloud](https://reflex.dev/hosting/). No infrastructure configuration, no build pipeline to wire up. For Jira API credentials, [use Reflex Cloud's secure credential storage](https://reflex.dev/use-cases/consulting/) instead of hardcoding them. Local development uses environment variables; production reads from the same variable names, so parity is automatic. + +### Secrets Management and Security + +Role-based access control (RBAC) makes sure team members access only the Jira data their role permits. Credentials are configured once at the project level and shared across every app in that workspace automatically. + +### Deployment Options for Enterprise Teams + +Organizations with compliance requirements around Jira data can [deploy entirely on-premises](https://reflex.dev/blog/on-premises-deployment/) or in a VPC environment via self-hosting, with the same development experience intact. For teams managing [multiple Jira integration apps across Kubernetes clusters](https://reflex.dev/blog/enterprise-ready-ai-app-builder/), Helm chart orchestration plugs directly into GitOps pipelines. Multi-region deployment handles globally distributed teams without extra configuration. Built-in OpenTelemetry tracing and ClickHouse log aggregation give you API call latency, error rates, and production logs out of the box. The full config reference lives at reflex.dev/docs/api-reference/config. + +## FAQ + +### Can I build a Jira web app without JavaScript? + +Yes. Reflex lets you build full Jira integrations in pure Python, writing both the frontend UI and backend API logic without touching JavaScript. The `jira` or `atlassian-python-api` SDK handles data fetching, while Reflex components render tables, forms, and dashboards entirely in Python code. + +### How to build a Python web app with Jira in 2026? + +Connect the Jira Python SDK to a Reflex state class, store credentials in environment variables, and use event handlers to fetch issues via JQL queries. Render results with `rx.data_table` and `rx.card` components, then deploy with `reflex deploy` - no separate frontend build required. + +### What's the difference between Reflex and Streamlit for Jira dashboards? + +Reflex uses event-based state updates that propagate changes instantly across the UI, while Streamlit's script rerun model re-executes your entire application on every interaction. For Jira apps with status transitions, assignee updates, or multi-step workflows, Reflex handles real-time state changes without memory leaks or full-page refreshes. + +### When should I deploy my Jira app on-premises vs Reflex Cloud? + +Deploy on-premises or in a VPC if your organization has compliance requirements around Jira data access or needs to keep credentials within your security perimeter. Reflex Cloud with multi-region deployment works well for teams without those constraints, offering the same development experience with faster setup. + +### How do Reflex computed vars work with Jira data? + +Computed vars automatically calculate metrics like open issue counts or sprint burndown totals from your Jira state variables, recalculating whenever the underlying data changes. Define them as properties on your state class using `@rx.var`, and they update reactively without manual refresh logic. diff --git a/blog/how-to-build-python-web-app-with-langchain.md b/blog/how-to-build-python-web-app-with-langchain.md new file mode 100644 index 000000000..efbedefb6 --- /dev/null +++ b/blog/how-to-build-python-web-app-with-langchain.md @@ -0,0 +1,159 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With LangChain in 2026" +title_tag: "Build Python Web App With LangChain 2026" +description: "Learn how to build a Python web app with LangChain in April 2026. Complete guide to creating AI-powered conversational interfaces without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "LangChain Python app, LangChain web app, RAG Python app, LLM chain app, LangChain integration, AI pipeline Python" + } +] +faq: [ + {"question": "Can I build a LangChain web app without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire application—including the UI, state management, and LangChain integration—in pure Python. You write your agent logic and web interface in the same language without touching React or any frontend framework."}, + {"question": "LangChain Streamlit vs Reflex for production apps?", "answer": "Streamlit's rerun model breaks under load with memory leaks and can't push server-side updates to the browser, making it unreliable for multi-step agent conversations. Reflex uses WebSocket-based state sync for real-time streaming responses and handles stateful agent workflows without the script re-execution overhead."}, + {"question": "How do I handle streaming responses from LangChain agents in the UI?", "answer": "Use yield statements inside your Reflex event handler while the agent generates output. Each yield pushes incremental updates to the UI through WebSocket connections, creating a token-by-token streaming experience without writing custom WebSocket code."}, + {"question": "What's the fastest way to deploy a LangChain app in 2026?", "answer": "Run `reflex deploy` from your terminal. The command provisions infrastructure, manages API secrets, and handles background job processing for long-running agent tasks. For teams with compliance requirements, self-hosted deployment using Kubernetes and Helm charts gives you full control over data residency."}, + {"question": "What LLM providers does LangChain support in 2026?", "answer": "LangChain natively supports OpenAI, Anthropic, and Google models. You can use GPT-5.4 for general-purpose agent work, Claude Opus 4.6 for frontier reasoning tasks, or Gemini 3.1 Pro for multimodal workflows, and switch between them with small config changes rather than rewriting your agent logic."}, + {"question": "How does Reflex handle state management for LangChain agents?", "answer": "Your LangChain agent lives inside a Reflex State class that holds the agent instance, conversation memory, and context that persists across user interactions. When users submit messages, Reflex event handlers call the agent directly and write responses back to state variables, with the UI reacting automatically."}, + {"question": "What are the key differences between building a chatbot and a production LangChain app?", "answer": "Production LangChain apps require long-running backend processes for multi-step reasoning, background job support for agent tasks that exceed typical request timeframes, and observability into token consumption and tool call success rates. They also need proper secrets management and conversation persistence across interactions."}, + {"question": "Can I add authentication to my LangChain web app?", "answer": "Yes. Reflex supports authentication features including sign-in with Google, so you can add user authentication to your LangChain-powered web app while keeping everything in Python."}, + {"question": "What is LangSmith Fleet and how does it help with agent management?", "answer": "LangSmith Fleet, added by March 2026, provides agent identity, sharing, and permissions management so teams can securely manage entire agent fleets across an organization. It handles workflow orchestration for agent workloads including long-running stateful execution and real-time streaming."}, + {"question": "How do I display what tools my LangChain agent is using?", "answer": "LangChain agents expose intermediate steps showing which tools were called and why. You can store these steps in a dedicated Reflex state variable and render them in an expandable UI component, giving users visibility into the agent's reasoning process and building trust in AI outputs."}, + {"question": "What conversation memory options does LangChain provide?", "answer": "LangChain provides conversation memory through components like ConversationBufferMemory, which can be stored in your Reflex state class to persist across page interactions. This enables the agent to remember prior turns in the conversation and maintain context throughout multi-step interactions."}, + {"question": "Why would I need background job processing for a LangChain app?", "answer": "LangChain agents perform multi-step reasoning and tool execution chains that can exceed typical request timeframes. Background job processing allows these long-running agent tasks to complete without timing out or blocking other requests, which is essential for production reliability."}, + {"question": "How does Reflex compare to React for building LangChain interfaces?", "answer": "Unlike React which requires JavaScript knowledge and managing a separate frontend codebase, Reflex lets you build the entire LangChain interface in pure Python using 60+ built-in components. This eliminates context switching and keeps your agent logic and UI in the same language and codebase."}, + {"question": "What monitoring capabilities do I need for production LangChain apps?", "answer": "Production LangChain apps need visibility into token consumption, agent reasoning paths, and tool call success rates. Using LangSmith Deployments paired with OpenTelemetry tracing allows you to trace execution flows and identify issues before users report them."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- LangChain agents handle memory and tool integration, but exposing them through a web UI typically requires learning React and managing a separate JavaScript frontend. + +- Reflex lets you build the LangChain logic and entire web interface in pure Python, with built-in support for streaming responses and real-time UI updates. + +- Production LangChain apps need long-running backend processes for multi-step reasoning, background job support for agent tasks, and observability into token consumption and tool call success rates. + +- Reflex is a full-stack Python framework that powers over 1 million applications and is used by 40% of Fortune 500 companies for building production-grade web apps without JavaScript. + +## Why Python Developers Are Building Web Apps With LangChain in 2026 + +LangChain has become the go-to framework for Python developers building AI agents that need memory, tool integration, and multi-step reasoning. It gives you composable building blocks for coordinating LLM calls with external data and chained workflows - things raw API calls simply can't handle cleanly. By March 2026, LangSmith Fleet added agent identity, sharing, and permissions, so teams can manage entire agent fleets across an organization securely. + +But there's a wall most Python developers hit. You can build a sophisticated LangChain agent in a weekend. Exposing it through a real web interface? That means learning React, managing a JavaScript frontend, and splitting your codebase into two separate worlds. For data scientists and ML engineers working with [AI app builders](https://reflex.dev/blog/top-7-enterprise-ai-app-builders/), that's a major detour. + +> + +"It's like Streamlit for adults. It's fast, it looks good, and we don't need to throw it away after prototyping." - Delta Global Head of Quant + +That's the gap Reflex fills. With Reflex, you write your LangChain logic and your entire web UI in pure Python. No JavaScript, no context switching, no frontend bottleneck. + +## What You'll Build: A Python Web App Powered by LangChain + +You'll build a [conversational AI assistant](https://reflex.dev/templates/chat-bot/) with a real browser-based interface. Users type a prompt, the message routes through a LangChain agent with conversation memory and tool access, and the response streams back in real-time with no page reloads or polling. + +According to JetBrains' 2026 LangChain tutorial, agents combine LLMs with tools to create systems that can reason about tasks, decide which tools to use at each step, analyze intermediate results, and work toward solutions iteratively. That's the pattern we're building around: a stateful agent that remembers prior turns and can call external tools when needed. + +LangChain supports OpenAI and Anthropic models natively, so you can swap in gpt-5-mini for speed or Claude Opus 4.6 for heavier reasoning without rewriting your agent logic. + +A few things worth flagging before we get into the build: + +- LangChain also supports RAG pipelines, document Q&A, and multi-agent orchestration with LangGraph, giving you room to grow the app well beyond a basic chatbot. + +- This guide focuses on the conversational agent pattern, as it covers the most common production use case and shows off the two things Reflex handles especially well: server-side state management and real-time streaming UI updates. + +## Connecting LangChain to Your Reflex App + +Reflex can use any Python library available via pip, so wiring LangChain into your app requires no special adapter or bridge. + +### Installing LangChain and LLM Provider SDKs + +Install LangChain alongside whichever provider SDK you're targeting. In 2026, most teams reach for Claude Opus 4.6 for frontier reasoning tasks, GPT-5.4 for general-purpose agent work, or Gemini 3.1 Pro when multimodal input is part of the workflow. Each provider ships its own Python SDK, and LangChain wraps them through a common interface, so switching models later is a small config change instead of a full rewrite. + +### Configuring API Keys and Project-Level Integrations + +Reflex's project-level integration configuration shares API keys across every app in a project automatically, eliminating the need to set credentials per app. This matters when you're running multiple LangChain-powered apps under the same project, since it eliminates credential duplication and permission drift. LLM provider keys for OpenAI, Anthropic, or Google get configured once and flow through to every app that needs them. + +### Wiring LangChain Agents into Reflex State + +Your LangChain agent lives inside a Reflex State class. The state holds the agent instance, conversation memory, and any context that needs to persist across user interactions. When a user submits a message, a Reflex event handler calls the agent directly, just like calling any Python function, and writes the response back to state variables. The UI reacts automatically. + +LangChain supports multiple [memory frameworks for AI agents](https://atlan.com/know/best-ai-agent-memory-frameworks-2026/), including built-in conversation buffers and external solutions like Mem0 and Zep for more sophisticated memory persistence across sessions. + +LangChain's agent abstraction is designed to get you started fast: a simple agent takes under 10 lines of code, while still giving you enough flexibility for extensive context engineering as [the app grows](https://reflex.dev/blog/structuring-a-large-app/). + +## Building the UI Around LangChain in Pure Python + +Reflex gives you 60+ [built-in components](https://reflex.dev/blog/custom-components/) to work with, so building a chat interface means composing Python functions without writing JSX or HTML. The patterns below cover the three pieces that matter most for a LangChain-powered chat app. + +### Creating Chat Components for Conversational Interfaces + +Your state class holds a list of message dictionaries, each with role, content, and timestamp fields. The UI iterates over that list and displays each message in the appropriate component. If you've worked with LangChain's `HumanMessage` and `AIMessage` schemas, the structure will feel familiar. Input fields, send buttons, and scroll containers are all standard Reflex components wired to event handlers in your state class. + +### Handling Streaming Responses from LangChain Agents + +LangChain agents support streaming output, and Reflex's WebSocket-based state sync pushes those tokens to the UI as they arrive. Inside your event handler, `yield` statements update the response variable incrementally, producing a ChatGPT-like streaming experience without writing custom WebSocket code. + +| LangChain Component | Reflex State Pattern | UI Update Method | +|---|---|---| +| Agent with tools | State method invoking `agent.run()` | Event handler updates state variable | +| Conversation memory | `ConversationBufferMemory` stored in state | Memory persists across page interactions | +| Streaming responses | Async generator with yield statements | Real-time token-by-token UI updates | +| Tool execution results | State variable holding tool outputs | Reactive component updates on change | + +### Displaying Agent Reasoning and Tool Calls + +LangChain agents expose intermediate steps showing which tools were called and why. According to langchain-tutorials.github.io, agents can observe results, reconsider, and call the same or different tool again in an iterative process. Storing these steps in a dedicated state variable and displaying them inside an expandable component gives users visibility into how the agent reached its answer. That transparency matters in production, where trust in AI outputs depends on being able to inspect the reasoning and understand the final response. + +## Deploying Your LangChain App to Production + +Getting a LangChain app running locally is one thing; keeping it stable under real traffic is another. Production deployment introduces concerns around secrets management, long-running processes, and observability that you need to plan for before users arrive. + +There are several deployment approaches worth considering, depending on your team's needs. + +### Self-Hosting vs. Managed Deployment + +For teams with compliance requirements in finance, healthcare, or government, [self-hosted deployments](https://reflex.dev/blog/on-premises-deployment/) using Kubernetes and Helm charts give you full control over where data lives and how credentials are managed. For most teams, a [managed hosting solution](https://reflex.dev/hosting/) that handles the infrastructure layer is the faster path. + +### Production Considerations for LangChain Applications + +LangChain agents are not stateless request handlers. Multi-step reasoning, tool execution chains, and conversation memory require [long-running backend processes](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) that stay alive across interactions. Any hosting solution you choose needs to support background job processing for agent tasks that exceed typical request timeframes. + +| Deployment Requirement | Managed Solution | Enterprise Option | +|---|---|---| +| API key security | Built-in secrets management | VPC deployment with customer-managed keys | +| Conversation persistence | Stateful backend with database support | On-premises with internal databases | +| Long-running agent tasks | Background job processing | Kubernetes/Helm charts for self-hosted control | +| Multi-region availability | Global infrastructure | Hybrid deployment across customer regions | +| Observability for LLM calls | Integrated monitoring and alerts | OpenTelemetry tracing and ClickHouse logs | + +### Monitoring LangChain Applications in Production + +Production LangChain apps need visibility into token consumption, agent reasoning paths, and tool call success rates. For teams already using LangSmith, [LangSmith Deployments](https://docs.langchain.com/langsmith/deployments) handles workflow orchestration for agent workloads including long-running stateful execution and real-time streaming. Pairing it with OpenTelemetry tracing lets you trace execution flows across both systems in parallel, so issues surface before users report them. + +## FAQ + +### Can I build a LangChain web app without learning JavaScript? + +Yes. Reflex lets you build the entire application, including the UI, state management, and LangChain integration, in pure Python. You write your agent logic and web interface in the same language without touching React or any frontend framework. + +### LangChain Streamlit vs Reflex for production apps? + +Streamlit's rerun model breaks under load with memory leaks and can't push server-side updates to the browser, making it unreliable for multi-step agent conversations. Reflex uses WebSocket-based state sync for real-time streaming responses and handles stateful agent workflows without the script re-execution overhead. + +### How do I handle streaming responses from LangChain agents in the UI? + +Use yield statements inside your Reflex event handler while the agent generates output. Each yield pushes incremental updates to the UI through WebSocket connections, creating a token-by-token streaming experience without writing custom WebSocket code. + +### What's the fastest way to deploy a LangChain app in 2026? + +Run `reflex deploy` from your terminal. The command provisions infrastructure, manages API secrets, and handles background job processing for long-running agent tasks. For teams with compliance requirements, self-hosted deployment using Kubernetes and Helm charts gives you full control over data residency. diff --git a/blog/how-to-build-python-web-app-with-linear.md b/blog/how-to-build-python-web-app-with-linear.md new file mode 100644 index 000000000..0b12f0c58 --- /dev/null +++ b/blog/how-to-build-python-web-app-with-linear.md @@ -0,0 +1,146 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Linear in 2026" +title_tag: "Build Python Web App With Linear (April 2026)" +description: "Learn to build a Python web app with Linear in April 2026. Create dashboards, manage issues, and deploy production-ready apps using Reflex and Linear API." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Linear Python app, Linear API web app, project management Python, Linear integration, issue tracker Python app" + } +] +faq: [ + {"question": "Can I build a Linear web app without JavaScript?", "answer": "Yes. Reflex lets you build complete Linear integrations in pure Python—frontend, backend, and API calls all in one language. The linear-api package handles GraphQL queries, and Reflex components handle the UI, so your Python team can ship a production Linear dashboard without touching JavaScript."}, + {"question": "Linear dashboard Streamlit vs Reflex?", "answer": "Streamlit gets you a prototype quickly but breaks down for production Linear dashboards: no real authentication, rigid layouts you can't customize, and the script rerun model makes interactive filtering feel slow. Reflex gives you full control over UI components, built-in auth support, and real-time updates over WebSocket, so the dashboard you build is actually ready to ship."}, + {"question": "How do I update Linear issues from a Reflex app?", "answer": "Import the linear-api package, initialize a client with your API key in your state class, and call SDK methods like `client.issues.update()` directly inside Reflex event handlers. When a user changes an issue status in a dropdown, the handler updates Linear via the API and syncs the UI automatically—all in Python functions on your state class."}, + {"question": "What's the fastest way to deploy a Linear dashboard in 2026?", "answer": "Run `reflex deploy` from your project directory. Reflex handles containerization, infrastructure setup, and multi-region deployment automatically, storing your Linear API key as an encrypted environment variable. The entire process takes minutes, and you get a production URL immediately without configuring servers or security manually."}, + {"question": "When should I self-host vs use Reflex Cloud for Linear apps?", "answer": "Use Reflex Cloud for standard deployments where you need fast setup and automatic scaling. Self-host when you're in finance, healthcare, or consulting and need Linear project data to stay inside your security perimeter—VPC deployment or on-premises keeps API credentials and workflow data in your own infrastructure with full secrets management control."}, + {"question": "Does Reflex support Linear's GraphQL API natively?", "answer": "Reflex runs on a FastAPI backend, so you can import and use the linear-api Python package directly in your event handlers. The package handles GraphQL queries through an object-oriented interface with dedicated resource managers, Pydantic models, and automatic pagination, making Linear API integration seamless."}, + {"question": "Can I filter Linear issues in real-time with Reflex?", "answer": "Yes. Store your Linear issues in a state variable, add computed vars to filter by priority or status, and connect them to search inputs with on_change handlers. Reflex's reactive rendering updates the table instantly over WebSocket without polling or page reloads."}, + {"question": "How does Reflex handle Linear API authentication?", "answer": "Store your Linear personal API key as an environment variable and reference it when initializing the linear-api client in your Reflex state class. This keeps credentials centralized across environments and prevents hardcoding sensitive keys in your codebase."}, + {"question": "What Linear data can I display in a Reflex dashboard?", "answer": "You can display issues, projects, cycle progress, assignees, priorities, and statuses by calling the linear-api SDK methods from Reflex event handlers. The SDK returns structured data that maps directly to Reflex table columns and card components."}, + {"question": "Can I create new Linear issues from a Reflex form?", "answer": "Yes. Build a form using Reflex's input and button components, then wire the submit button to an event handler that calls client.issues.create() with the form data. The new issue writes to Linear via the API and appears in your UI immediately through reactive state updates."}, + {"question": "Does Reflex support Linear webhooks for real-time events?", "answer": "Yes. You can expose custom API endpoints through Reflex's API routes to receive Linear webhook events. Since Reflex runs on FastAPI, webhook handlers can update state and push changes to connected clients over WebSocket automatically."}, + {"question": "How do I show cycle progress from Linear in Reflex?", "answer": "Fetch cycle data using the linear-api client, store it in a state variable, and render it through Reflex card components. You can display active cycle names, completion percentages, and open issue counts as a live snapshot that updates whenever state changes."}, + {"question": "Can multiple users view the same Linear dashboard simultaneously?", "answer": "Yes. Each connected user gets their own session, but since Reflex manages state reactively and updates over WebSocket, changes from one user propagate to all connected clients instantly without manual synchronization code."}, + {"question": "What happens if the Linear API call fails in a Reflex app?", "answer": "The linear-api package includes built-in error handling, and you can wrap SDK calls in try-except blocks within your Reflex event handlers. Use state variables to store error messages and display them in the UI through conditional rendering, giving users immediate feedback when API operations fail."}, + {"question": "Can I customize the styling of Linear data in Reflex?", "answer": "Yes. Reflex components accept style props directly in Python, so you can customize colors, spacing, fonts, and layouts for your Linear issue tables, cards, and forms without writing CSS or JavaScript."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build a full-stack Linear dashboard in pure Python using Reflex and the linear-api package + +- Reflex handles real-time UI updates over WebSocket when Linear data changes, no polling needed + +- Deploy to production with `reflex deploy` or self-host for compliance-sensitive industries + +- Reflex is an open-source Python framework that lets you build web apps entirely in Python without JavaScript + +## Why Python Developers Are Building Web Apps With Linear in 2026 + +Linear has become the go-to issue tracker for engineering teams that want speed without the clutter of older tools. But the moment a team needs a custom view, a cross-team dashboard, or any workflow automation beyond what Linear's UI ships, they hit a wall. The data is there, accessible through Linear's GraphQL API, but getting it into a usable web interface is where things get messy. + +The typical paths are frustrating. A [Streamlit dashboard](https://reflex.dev/blog/reflex-streamlit/) gets you something working in an afternoon, but you quickly run into its limitations: no real auth, rigid layouts, and a rerun model that makes interactive workflows feel janky. Going full React means your Python team is now context-switching into JavaScript just to display their own project data. Neither option is actually good. + +This is where Reflex fits cleanly. You can build production-ready UIs with Linear's API entirely in Python. The [linear-api](https://pypi.org/project/linear-api/) package makes this even smoother, offering an object-based design with dedicated resource managers, Pydantic models for issues and projects, automatic pagination, and solid error handling, so you spend time building your app, not parsing API responses. + +The result is something neither Streamlit nor a custom React frontend gives you: a maintainable, customizable Linear dashboard that your whole Python team can read, debug, and extend. + +## What You'll Build: A Python Web App Powered by Linear + +You're [building a Linear issue dashboard](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/): a web app that pulls your team's issues from Linear's GraphQL API and displays them through Reflex's component system using tables, status cards, and a project progress view. + +Here's what the finished product includes: + +- A filterable issue table with status, assignee, and priority columns so your team can slice through backlog noise quickly + +- Cards showing active cycle progress and open issue counts by project, giving you a live snapshot of where things stand + +- Create and update forms that write back to Linear via the API, so the app is fully read-write from day one + +- Real-time UI updates over WebSocket whenever state changes, with no polling or page reloads required + +That last point is worth calling out. Reflex's state management keeps your Linear data in sync with the UI automatically. Event handlers respond to user actions, update state, and the interface reflects the change immediately. + +The result skips the prototyping phase entirely. Because Reflex apps come with proper auth support, real state management, and deployment built in, what you build here is ready to ship as-is without needing a separate production rewrite after the demo. + +## Connecting Linear to Your Reflex App + +Linear's GraphQL API authenticates via personal API keys, which you generate directly from your workspace settings. Store your key as an environment variable and reference it inside your Reflex state class at initialization. This keeps credentials in one place across your entire project, so there is no drift between environments or apps. The [Linear GraphQL API documentation](https://linear.app/developers/graphql) covers authentication, schema structure, and query patterns in detail. + +### Calling Linear's Python SDK from Event Handlers + +Reflex's FastAPI backend means any pip-installable package works natively. Import the `linear-api` package, initialize a client with your credentials, and call SDK methods directly inside Reflex event handlers. Data fetching, issue creation, status updates: all of it lives in Python methods on your state class. You can also expose custom endpoints through Reflex's API routes if you need webhook support for real-time Linear events. + +> + +Linear's GraphQL API and webhooks let you extend Linear's functionality beyond what the product ships out of the box, which is exactly the gap a Reflex app fills. + +| Linear API Operation | Python SDK Method | Reflex Event Handler Pattern | +|---|---|---| +| Fetch team issues | `client.issues.get_by_team()` | `on_mount` handler to load initial data | +| Create new issue | `client.issues.create()` | Button `on_click` handler with form data | +| Update issue status | `client.issues.update()` | Dropdown `on_change` handler with status value | +| Search issues | `client.issues.get()` with filters | Search input `on_change` with debounce | + +## Building the UI Around Linear in Pure Python + +With your Linear data flowing through state, the UI layer is where Reflex's component system does the heavy lifting. You're working in one Python codebase, one state class, one mental model throughout. + +### Displaying Linear Issues in Data Tables + +[Reflex's table components](https://reflex.dev/blog/using-table-component/) accept your state variables directly as data sources. Store the list of issues returned by the Linear SDK in a state var, and the table rows populate automatically through reactive updates. Columns for issue identifier, title, status, assignee, and priority map one-to-one to the fields the SDK returns. Add computed vars on top to filter or sort by priority without touching the raw data. + +### Creating Interactive Forms for Issue Management + +[Form components in Reflex](https://reflex.dev/blog/implementing-sign-in-with-google/) handle text inputs, dropdowns, and buttons through the same event handler pattern. When a user submits a new issue, the handler calls the Linear SDK, writes the result back to Linear, and appends it to your local issues var in one Python function. Loading states, validation errors, and success notifications are all handled in the same class with no JavaScript needed. + +### Real-Time Updates Without Page Refreshes + +When an event handler modifies state, Reflex pushes the update to the browser over WebSocket immediately. There is no polling interval to configure, no manual DOM update to trigger. Compare that to a Streamlit app, where every interaction re-runs the entire script, or a [custom React frontend](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/), where you wire WebSocket subscriptions by hand. In Reflex, the reactive loop is built into the framework. Create an issue, and the table reflects it instantly. + +## Deploying Your Linear App to Production + +Reflex gives you two paths to get your Linear app in front of users, and both handle the security considerations that come with storing API credentials. + +Running ``[reflex deploy](https://reflex.dev/hosting/) from your project directory handles containerization, infrastructure provisioning, and multi-region rollout automatically. Linear API keys get stored as encrypted environment variables, injected at runtime, never hardcoded. The full deployment quick start docs and CLI reference cover all available options. + +Teams in finance, healthcare, or consulting handling sensitive project data can [deploy entirely within their own infrastructure](https://reflex.dev/blog/on-premises-deployment/). [Self-hosting](https://reflex.dev/blog/structuring-a-large-app/) keeps Linear credentials and workflow data inside your security perimeter. + +| Deployment Method | Use Case | Linear API Key Storage | +|---|---|---| +| Reflex Cloud | Standard cloud deployment | Encrypted environment variables | +| VPC Deployment | Enterprise security requirements | Customer-managed secrets vault | +| On-Premises | Compliance-sensitive industries | Internal secrets management system | + +## FAQ + +### Can I build a Linear web app without JavaScript? + +Yes. Reflex lets you build complete Linear integrations in pure Python: frontend, backend, and API calls all in one language. The linear-api package handles GraphQL queries, and Reflex components handle the UI, so your Python team can ship a production Linear dashboard without touching JavaScript. + +### What's the difference between Streamlit and Reflex for Linear dashboards? + +Streamlit gets you a prototype quickly but breaks down for production Linear dashboards: no real authentication, rigid layouts you can't customize, and the script rerun model makes interactive filtering feel slow. Reflex gives you full control over UI components, built-in auth support, and real-time updates over WebSocket, so the dashboard you build is actually ready to ship. + +### How do I update Linear issues from a Reflex app? + +Import the linear-api package, initialize a client with your API key in your state class, and call SDK methods like `client.issues.update()` directly inside Reflex event handlers. When a user changes an issue status in a dropdown, the handler updates Linear via the API and syncs the UI automatically, all in Python functions on your state class. + +### What's the fastest way to deploy a Linear dashboard in 2026? + +Run `reflex deploy` from your project directory. Reflex handles containerization, infrastructure setup, and multi-region deployment automatically, storing your Linear API key as an encrypted environment variable. The entire process takes minutes, and you get a production URL immediately without configuring servers or security manually. + +### When should I self-host vs use Reflex Cloud for Linear apps? + +Use Reflex Cloud for standard deployments where you need fast setup and automatic scaling. Self-host when you're in finance, healthcare, or consulting and need Linear project data to stay inside your security perimeter. VPC deployment or on-premises keeps API credentials and workflow data in your own infrastructure with full secrets management control. diff --git a/blog/how-to-build-python-web-app-with-supabase.md b/blog/how-to-build-python-web-app-with-supabase.md new file mode 100644 index 000000000..cfa18fac3 --- /dev/null +++ b/blog/how-to-build-python-web-app-with-supabase.md @@ -0,0 +1,154 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Supabase in 2026" +title_tag: "Python Web App With Supabase April 2026" +description: "Learn how to build a Python web app with Supabase in April 2026. Complete guide to creating full-stack apps with PostgreSQL, auth, and real-time updates." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Supabase Python app, Supabase web app, Supabase integration Python, Postgres Python app, real-time Python app, Supabase tutorial" + } +] +faq: [ + {"question": "Can I build a Python web app with Supabase without JavaScript?", "answer": "Yes. Reflex lets you build full-stack web apps in pure Python, handling both your Supabase database calls and UI components in a single codebase without writing any JavaScript."}, + {"question": "How do I connect Supabase to a Reflex app?", "answer": "Install the `supabase-py` library, store your project URL and API key in environment variables, then call `create_client()` inside your Reflex State class constructor. Event handlers inherit the authenticated client and can query, insert, update, or delete records directly."}, + {"question": "What's the best framework for building a Supabase dashboard in Python?", "answer": "Reflex handles both backend database logic and frontend UI in pure Python, while alternatives like Flask or FastAPI require a separate React layer. If you want a single Python codebase that talks to Supabase and renders the interface, Reflex removes the stack split entirely."}, + {"question": "When should I deploy my Reflex app to the same AWS region as my Supabase database?", "answer": "Always. Supabase runs exclusively on AWS regions, and deploying your Reflex app to the closest matching region cuts query latency. Geographic mismatches add tens of milliseconds per request, which compounds quickly under production traffic."}, + {"question": "Does Supabase support real-time database updates in Python applications?", "answer": "Yes. Supabase provides real-time subscriptions through the async Python client using `acreate_client()`. In Reflex apps, you can subscribe to PostgreSQL changes and push updates to connected browsers through Reflex's WebSocket layer without additional infrastructure or polling."}, + {"question": "What authentication methods does Supabase Auth support with Reflex?", "answer": "Supabase Auth uses JWTs and works alongside Row Level Security to restrict database access. In Reflex, you build login forms using input and button components, call `sign_in_with_password()` in an event handler, and store the session token in state to manage authentication flows entirely in Python."}, + {"question": "How does Reflex handle database credentials securely when connecting to Supabase?", "answer": "Reflex loads Supabase project URLs and API keys from environment variables at initialization. In production, credentials are stored in Reflex Cloud's secrets manager and never exposed in source code or the browser, since all database calls run server-side through the compiled FastAPI backend."}, + {"question": "Can I use Supabase Edge Functions with a Reflex application?", "answer": "Yes. You can invoke Supabase Edge Functions from Reflex event handlers using `supabase.functions.invoke(\"function-name\")`. This lets you trigger background jobs or serverless functions directly from your Python application logic."}, + {"question": "What database operations can I perform on Supabase through Reflex event handlers?", "answer": "Reflex event handlers can perform all standard database operations including select queries, inserts, updates, and deletes using the supabase-py client methods like `supabase.table(\"users\").select(\"*\").execute()`. All operations run server-side with your database credentials never reaching the browser."}, + {"question": "How do I handle file uploads to Supabase Storage in a Reflex app?", "answer": "You can handle file uploads through Reflex event handlers using `supabase.storage.from_(\"bucket\").upload()`. The file upload component triggers an event handler that interacts with Supabase Storage, keeping all the logic in Python without writing separate frontend code."}, + {"question": "What happens when a Supabase database call fails in a Reflex event handler?", "answer": "When a database call fails, you can catch the exception in your event handler and update an error state variable. Reflex then automatically displays the error inline through alert components, providing user feedback without manual error handling in the UI layer."}, + {"question": "Does Reflex require a separate REST API layer between the app and Supabase?", "answer": "No. Reflex event handlers call the Supabase client directly from Python, eliminating the need for separate Flask or FastAPI middleware. The same Python file that defines your UI components also queries your Supabase database, removing the traditional API layer entirely."}, + {"question": "How does Row Level Security in Supabase work with Reflex applications?", "answer": "Supabase Row Level Security ensures your database only returns records the authenticated user is allowed to see. When Reflex event handlers query Supabase using authenticated sessions, RLS policies are automatically enforced, so you get database-level access control without additional application logic."}, + {"question": "Can I deploy a Reflex Supabase app on-premises for compliance requirements?", "answer": "Yes. Reflex offers VPC deployment and on-premises options for compliance-heavy industries like finance and healthcare. This addresses regulatory requirements that Supabase's cloud-only AWS infrastructure cannot satisfy on its own."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Reflex lets you build full-stack web apps with Supabase in pure Python. No React frontend required. + +- You query PostgreSQL, handle auth, and manage real-time updates through Python event handlers that update the UI automatically. + +- Deploy to production with VPC options and on-prem support for compliance-heavy industries like finance and healthcare. + +- Reflex is an open-source Python framework with 28,000+ GitHub stars, used by 40% of Fortune 500 companies for internal tools. + +## Why Python Developers Are Building Web Apps With Supabase in 2026 + +Supabase gives you a full PostgreSQL database alongside authentication, instant APIs, storage, Edge Functions, and [real-time subscriptions](https://supabase.com/) out of the box. For Python developers who already think in SQL and want production-ready database infrastructure, that's a compelling package. The problem has always been what comes after: you still need a frontend to surface all that data. + +The traditional path forces a stack split. You write a Flask or FastAPI backend to query Supabase, then build a separate React application to display results. That's two codebases, two deployment pipelines, and one very frustrated Python developer who just wanted to ship something. + +Reflex removes that split entirely. With Reflex, the same Python file that calls your Supabase tables also defines your UI components and manages application state. There's no JavaScript layer to write, no REST middleware to maintain, and no context-switching between languages mid-feature. You call Supabase through standard Python functions, and Reflex handles everything from state sync to browser display underneath. + +The result is a genuinely [full-stack Python workflow](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/) where Supabase handles the backend infrastructure while Reflex handles the interface. + +## What You'll Build: A Python Web App Powered by Supabase + +The app we're building is a data dashboard that reads from a Supabase PostgreSQL database and lets users view, create, update, and delete records through a clean UI, all written in Python. + +Here's what the finished app covers: + +- A live data table pulling records from Supabase, powered by Reflex's component library + +- Create, update, and delete operations triggered from UI components + +- User authentication through Supabase Auth, with credentials stored in environment variables + +- Reactive state that updates the UI automatically when data changes, no manual API wiring required + +Supabase exposes database access through REST and GraphQL Data APIs with Row Level Security (RLS), which means your app only ever fetches what the authenticated user is allowed to see. Your Reflex event handlers call those APIs directly, populate state variables, and the UI updates on its own. No polling loops. No client-side fetch calls scattered across components. + +The pattern here transfers cleanly to other use cases. Whether you're building a user management system, a CMS, or an analytics dashboard backed by PostgreSQL, the core integration approach remains consistent across all of them. + +## Connecting Supabase to Your Reflex App + +Getting Supabase talking to Reflex takes three steps: install the client, configure credentials, and wire up your State class. Here's how each piece fits together. + +### Installing the Python Client and Project Configuration + +The `supabase-py` library lets Python apps interact with PostgreSQL databases, listen to database changes, invoke Edge Functions, and [handle authentication](https://reflex.dev/blog/implementing-sign-in-with-google/). Install it alongside Reflex, then store your Supabase project URL and API key in environment variables. Reflex loads these at initialization, and since integrations are configured at the project level, those credentials are shared automatically across every app in that project. No per-app reconfiguration needed. + +### Initializing the Supabase Client in State Classes + +The `create_client()` method is the entrypoint to all Supabase functionality. Call it inside your Reflex State class constructor so every event handler inherits the authenticated client. Pulling credentials from environment variables keeps API keys out of source code while letting you swap configs between development and production without touching application logic. + +### Querying Data Through Event Handlers + +Event handlers call Supabase client methods to fetch, insert, update, or delete records, storing results in state variables that drive UI updates. Because [Reflex compiles to a FastAPI backend](https://reflex.dev/blog/reflex-architecture/), those calls run server-side. Your database credentials never reach the browser. + +| Supabase Feature | Reflex Integration Point | Python Method Example | +|---|---|---| +| PostgreSQL Database | State class event handlers | `supabase.table("users").select("*").execute()` | +| Authentication | Login page event handler | `supabase.auth.sign_in_with_password()` | +| Real-time subscriptions | Async state updates | `supabase.channel().on_postgres_changes().subscribe()` | +| Storage | File upload event handler | `supabase.storage.from_("bucket").upload()` | +| Edge Functions | Background job trigger | `supabase.functions.invoke("function-name")` | + +## Building the UI Around Supabase in Pure Python + +With the Supabase client wired into your State class, building the interface is a matter of mapping state variables to Reflex components. No JavaScript, no hooks, no manual DOM updates. + +There are four key areas where this integration pays off most clearly. + +### Displaying Database Records with Reflex Components + +Define state variables as Python lists holding Supabase query results, then pass them as props to [Reflex table or list components](https://reflex.dev/blog/using-table-component/). When an event handler assigns new data to `self.products`, the UI updates automatically. The [supabase-py client](https://github.com/supabase/supabase-py) supports querying Postgres with authentication, security policies, file storage, and real-time streaming, while [Reflex removes the web framework layer](https://reflex.dev/blog/reflex-streamlit/) so you work with state variables and component props directly. + +### Handling User Input and Database Mutations + +Reflex form components bind to state class attributes, keeping inputs synchronized without manual event listeners. When a form submits, the event handler receives the data and calls the appropriate Supabase insert, update, or delete operation. Exceptions from failed database calls update an error state variable that displays inline in alert components, all server-side, all Python. + +### Real-Time Updates Without WebSocket Configuration + +[Real-time in Python](https://supabase.com/docs/reference/python/introduction) works with the async client via `acreate_client()`. Supabase subscribes to PostgreSQL changes while Reflex's WebSocket layer pushes those updates to every connected browser. [Background tasks](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/) handle incoming events and update state variables that refresh the UI, requiring no additional infrastructure or polling. + +### Integrating Authentication UI + +[Supabase Auth](https://supabase.com/docs/guides/auth) uses JWTs and works alongside Row Level Security so your database only returns what the authenticated user can access. Build a login form with Reflex input and button components, call `sign_in_with_password()` in an event handler, then store the session token in state. [Background task support and protected route patterns](https://reflex.dev/blog/structuring-a-large-app/) handle the rest, keeping unauthorized users away from sensitive pages without leaving Python. + +## Deploying Your Supabase App to Production + +Once your app works locally, deploying is straightforward. Credentials stay in [Reflex Cloud's](https://reflex.dev/hosting/) secrets manager, never in source code. + +| Deployment Feature | Reflex Implementation | Supabase Configuration | +|---|---|---| +| API Credentials | Environment variables in Reflex Cloud | Project API keys from dashboard | +| Regional Scaling | Multi-region Reflex Cloud hosting | Single region with read-replicas on Pro/Enterprise | +| Connection Pooling | FastAPI async server with configurable workers | PgBouncer transaction mode pooler | +| Monitoring | OpenTelemetry tracing and logs | Supabase dashboard metrics and alerts | +| Security Compliance | VPC deployment and on-prem options | Row Level Security and database encryption | + +Since Supabase runs exclusively on AWS regions worldwide, deploy your Reflex app to the closest matching AWS region to cut query latency. Even small geographic mismatches between your app server and database can add tens of milliseconds to every request, which compounds quickly at scale. + +For compliance-heavy industries, Reflex's VPC and on-premises deployment options cover requirements that Supabase alone cannot satisfy. Before going live, run the [Supabase Index Advisor](https://supabase.com/changelog) to catch missing indexes that silently slow queries as your data grows. These are the kinds of performance gaps that only surface under real production traffic, so catching them early saves extensive troubleshooting later. + +## FAQ + +### Can I build a Python web app with Supabase without JavaScript? + +Yes. Reflex lets you build full-stack web apps in pure Python, handling both your Supabase database calls and UI components in a single codebase without writing any JavaScript. + +### How do I connect Supabase to a Reflex app? + +Install the `supabase-py` library, store your project URL and API key in environment variables, then call `create_client()` inside your Reflex State class constructor. Event handlers inherit the authenticated client and can query, insert, update, or delete records directly. + +### What's the best framework for building a Supabase dashboard in Python? + +Reflex handles both backend database logic and frontend UI in pure Python, while alternatives like Flask or FastAPI require a separate React layer. If you want a single Python codebase that talks to Supabase and displays the interface, Reflex removes the stack split entirely. + +### When should I deploy my Reflex app to the same AWS region as my Supabase database? + +Always. Supabase runs exclusively on AWS regions, and deploying your Reflex app to the closest matching region cuts query latency. Geographic mismatches add tens of milliseconds per request, which compounds quickly under production traffic. diff --git a/blog/python-web-app-azure-auth-microsoft-entra-id.md b/blog/python-web-app-azure-auth-microsoft-entra-id.md new file mode 100644 index 000000000..0b93f3280 --- /dev/null +++ b/blog/python-web-app-azure-auth-microsoft-entra-id.md @@ -0,0 +1,160 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Azure Auth / Microsoft Entra ID (Azure AD) in 2026" +title_tag: "Python Web App With Azure Auth (April 2026)" +description: "Learn to build Python web apps with Azure Auth and Microsoft Entra ID in April 2026. Server-side SSO, RBAC, and OAuth integration without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Azure Auth Python app, Microsoft Entra ID Python, Azure AD web app, SSO Python app, enterprise auth Python" + } +] +faq: [ + {"question": "Can I build a Python web app with Azure Auth without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire web app—frontend, backend, and auth integration—in pure Python. You import MSAL or any OAuth library directly into your event handlers, wire it to Reflex state, and never touch JavaScript."}, + {"question": "How do I register my Reflex app with Microsoft Entra ID?", "answer": "In the Azure Portal, go to App registrations and create a new registration. Set your redirect URIs for local and production environments, generate a client secret under Certificates & secrets, and note your tenant ID and client ID. Reflex uses the authorization code flow since all auth runs server-side."}, + {"question": "What's the difference between implementing Azure Auth in Reflex versus a React app?", "answer": "Reflex handles all auth logic server-side in Python, so client secrets never touch the browser and session management lives in Python state variables. React apps split auth between frontend and backend, requiring separate token storage, expiration handling, and cross-origin configuration."}, + {"question": "When should I deploy with VPC instead of standard cloud hosting for Azure Auth apps?", "answer": "If your organization operates in regulated industries like finance or healthcare, or if compliance requires keeping auth flows inside customer-controlled networks, VPC deployment routes Entra ID integration through private network infrastructure while maintaining the same Python codebase."}, + {"question": "Does role-based access control work with Microsoft Entra ID groups in Reflex?", "answer": "Yes. Group memberships and custom roles from Entra ID appear in the ID token claims, which Reflex reads into a `user_roles` state variable. You check that list in Python to show or hide admin panels, data views, and protected routes based on role membership."}, + {"question": "What authentication flow does Reflex use with Microsoft Entra ID?", "answer": "Reflex uses the OAuth 2.0 authorization code flow with OpenID Connect. All authentication logic runs server-side in Python, meaning the client secret never touches the browser and session management is handled entirely on the backend through Reflex state variables."}, + {"question": "How does Reflex handle user session management after Azure Auth login?", "answer": "Reflex stores user claims like name, email, and roles as Python state variables on the backend after parsing the Entra ID token. These state variables persist across page navigations throughout the session and are server-managed, eliminating the need for client-side token juggling."}, + {"question": "Can I use existing Python OAuth libraries with Reflex for Azure Auth?", "answer": "Yes. Because Reflex apps are pure Python, you can import any OAuth library like MSAL, Authlib, or custom implementations directly into your event handlers without adapter layers or wrappers."}, + {"question": "What happens when an unauthenticated user tries to access a protected route?", "answer": "Protected routes in Reflex check the is_authenticated state variable before rendering. Unauthenticated users see a login button instead of the protected content, with the logic handled in Python functions that evaluate state and return different components accordingly."}, + {"question": "Where should I store my Azure client secrets in a Reflex production deployment?", "answer": "Client secrets and tenant IDs should be stored in encrypted environment variables, never in source control. Production credentials should stay isolated from your dev environment while sharing the same underlying architecture to prevent cross-environment auth issues."}, + {"question": "Does my Reflex app handle MFA or does Entra ID manage it?", "answer": "Entra ID handles all authentication complexity including MFA, conditional access, and identity protection. Your Reflex app simply trusts the token it receives, requiring no additional code to support multi-factor authentication."}, + {"question": "What information from Entra ID can I display in my Reflex app UI?", "answer": "Your Reflex event handler reads the MSAL response and assigns claims directly to state variables like user_name, user_email, and user_roles. Components reference these variables directly without manual JSON parsing or token decoding."}, + {"question": "How do I configure Azure Auth credentials in a Reflex project?", "answer": "Reflex handles Azure credentials at the project level with four required values: client ID, client secret, tenant ID, and redirect URI. You configure them once and every app in that project inherits them automatically."}, + {"question": "What compliance considerations should I know for deploying Azure Auth apps in 2026?", "answer": "Microsoft Entra ID has 5 breaking changes in 2026 with hard deadlines covering password policies, Conditional Access updates, and legacy auth deprecation. Production deployments should account for these changes proactively to maintain compliance."}, + {"question": "Can I deploy a Reflex app with Azure Auth in air-gapped environments?", "answer": "Yes. On-premises deployments support air-gapped environments where Entra ID federates through internal OIDC providers using Helm chart orchestration, providing full data sovereignty while maintaining the same Python codebase."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Azure Auth connects to Reflex apps through pure Python, with no JavaScript needed for SSO or RBAC. + +- OAuth flow runs server-side with MSAL, storing user claims as Python state variables. + +- Protected routes check authentication status in Python functions before displaying components. + +- Reflex builds production-grade web apps with enterprise authentication entirely in Python. + +## Why Python Developers Are Building Web Apps With Azure Auth / Microsoft Entra ID (Azure AD) in 2026 + +[Microsoft Entra ID](https://reflex.dev/blog/microsoft-azure-authentication/) that controls who can access applications, data, and resources. Microsoft made the rebranding from Azure AD official in 2023 as part of a broader push to unify its security products under the Entra umbrella, but the core functionality that enterprises depend on (SSO, conditional access, and directory management) stayed intact. + +For Python teams, that creates a real problem. You've built a solid internal tool or data app in Python. It works. Now someone from IT asks about SSO integration, audit trails, and role-based access controls. Suddenly, you're staring down a React frontend you didn't ask to write. + +This is exactly where most Python data scientists and ML engineers hit a wall. The authentication logic itself isn't the hard part. The hard part is wiring it into a production frontend without handing the entire project off to a web developer who doesn't know your data model. + +Reflex removes that handoff. Because we build the entire stack in pure Python, you get enterprise-grade Azure Auth integrated directly into your app without touching JavaScript. SSO, RBAC, and session management all live alongside your backend logic, in the same language you already know. For enterprise teams needing compliance-ready auth, that makes a real difference. + +## What You'll Build: A Python Web App Powered by Azure Auth / Microsoft Entra ID (Azure AD) + +By the end of this guide, you'll have a working multi-page Python web app where Azure Auth handles identity and Reflex manages everything else. No JavaScript. No separate frontend codebase. + +Here's what the app covers: + +- A public landing page with a "Sign in with Microsoft" button that kicks off the auth flow (similar to [implementing Sign in with Google](https://reflex.dev/blog/implementing-sign-in-with-google/)) + +- OAuth 2.0 + OpenID Connect redirect flow through Microsoft's login portal + +- Callback handling that parses the Entra ID token and stores user claims in Reflex state + +- Protected routes that block unauthenticated access automatically + +- Role-based UI controls that show or hide content based on group membership from the token + +The auth pattern follows the standard OIDC flow. The user clicks login, gets redirected to Microsoft, authenticates there, and returns with a token. Reflex picks up that token on the backend, extracts claims like name, email, and assigned roles, and stores them as Python state variables. From that point, every page in the app can read from that state and render accordingly. + +> + +Because all state lives on the backend in Reflex, there is no client-side token juggling. The session is server-managed, which is critical for [enterprise security reviews](https://reflex.dev/blog/enterprise-ready-ai-app-builder/). + +[SSO, MFA, Conditional Access, and identity protection](https://netwrix.com/en/resources/blog/what-is-entra-id/) are all handled on the Microsoft side by Entra ID itself. Your Reflex app simply trusts the token it receives. + +## Connecting Azure Auth / Microsoft Entra ID (Azure AD) to Your Reflex App + +Getting Azure Auth wired into Reflex involves three moving parts: registering your app in Azure, configuring credentials in Reflex, and mapping the OAuth flow to Reflex's state pattern. + +### Registering Your Application in Microsoft Entra ID + +In the Azure Portal, go to App registrations and select New registration. Give the app a name, choose your supported account types, and set your redirect URIs (one for local development and one for production). Then generate a client secret under Certificates & secrets. Note your tenant ID, client ID, and client secret. Reflex uses the authorization code flow since all auth logic runs server-side in Python, so you never need a public client configuration. + +### Project-Level Integration Configuration in Reflex + +Reflex handles Azure credentials at the project level, so you configure them once and every app in that project inherits them automatically. Your four required values are client ID, client secret, tenant ID, and redirect URI. Because Reflex apps are pure Python, any OAuth library (MSAL, Authlib, or a custom implementation) can be imported directly into your event handlers. No adapter layers needed. + +### OAuth Flow Architecture in Reflex State + +The flow maps cleanly onto Reflex's event handler pattern. A login handler constructs the Microsoft authorization URL and triggers the redirect. A callback route receives the authorization code, and a second handler exchanges it for tokens using MSAL. All of this runs entirely server-side, which means the [client secret never touches the browser](https://reflex.dev/blog/structuring-a-large-app/). User claims like name, email, and roles get stored as Python state variables that persist across page navigations throughout the session. + +## Building the UI Around Azure Auth / Microsoft Entra ID (Azure AD) in Pure Python + +With auth connected, the UI layer becomes straightforward. Reflex state variables drive everything: what displays, what's hidden, and what gets passed to components as props. + +### Protected Routes and Conditional Display + +Every route in your app checks `is_authenticated` before showing anything. Unauthenticated users see a login button. Authenticated users see their dashboard. The logic lives in Python functions that check state variables and return different components accordingly, with no middleware or route guards written in a separate config file. + +### Displaying User Information from Entra ID Claims + +[Entra ID provides single sign-on](https://en.wikipedia.org/wiki/Microsoft_Entra_ID), including password, MFA, smart card, and certificate-based authentication. All of that complexity resolves into a token. Your Reflex event handler reads the MSAL response and assigns claims directly to state vars: `user_name`, `user_email`, `user_roles`. Components reference those vars directly, with no JSON parsing or manual decoding required, making it easy to build [compliant healthcare apps](https://reflex.dev/use-cases/healthcare/). + +### Role-Based Access Control in the UI + +Group memberships and custom roles travel inside the ID token and land in a `user_roles` list in Reflex state. [Admin panels](https://reflex.dev/blog/build-python-admin-panels-internal-tools-guide/), sensitive data views, and write operations render only when the right role is present. Because this check happens in Python, it's auditable, testable, and readable without browser DevTools. + +| Authentication Element | Entra ID Provides | Reflex State Manages | UI Component Displays | +|---|---|---|---| +| User Identity | ID token with email, name | user_email, user_name state vars | Welcome message, avatar | +| Session Status | Access token expiration | is_authenticated boolean | Login/logout buttons | +| Authorization | Roles and groups in token claims | user_roles list | Protected route access | +| Multi-Factor Auth | MFA via Conditional Access | No additional code required | Transparent to app | + +## Deploying Your Azure Auth / Microsoft Entra ID (Azure AD) App to Production + +When pushing your app to production, the first step is registering your production domain as a redirect URI in the Entra ID app registration. Microsoft will reject OAuth callbacks from unregistered domains, so this must be done before deployment. + +Client secrets and tenant IDs belong in encrypted environment variables, never in source control. Once configured, you can [deploy with a single command](https://reflex.dev/hosting/). Production credentials should stay isolated from your dev environment while sharing the same underlying architecture to prevent accidental cross-environment auth issues. + +There are also important compliance considerations to keep in mind. [Entra ID's 5 breaking changes in 2026](https://www.epcgroup.net/blog/microsoft-entra-id-changes-2026-admin-action-plan) cover password policies, Conditional Access updates, and legacy auth deprecation. Production deployments should account for these proactively. + +For finance, healthcare, and other compliance-heavy industries, VPC and [on-premises deployments](https://reflex.dev/blog/on-premises-deployment/) keep auth flows inside customer-controlled networks. Helm chart orchestration supports air-gapped environments where Entra ID federates through internal OIDC providers. + +| Deployment Option | Use Case | Entra ID Integration | Security Features | +|---|---|---|---| +| Cloud Hosted | Standard SaaS | Public Entra ID endpoint | Encrypted secrets, multi-region | +| VPC Deployment | Finance and healthcare | Private network routing | Customer-controlled infrastructure | +| On-Premises | Air-gapped environments | Internal OIDC federation | Full data sovereignty | + +Each deployment path carries different tradeoffs between convenience and control, so the right choice depends on your compliance requirements and where your user data needs to reside. + +## FAQ + +### Can I build a Python web app with Azure Auth without learning JavaScript? + +Yes. Reflex lets you build the entire web app (frontend, backend, and auth integration) in pure Python. You import MSAL or any OAuth library directly into your event handlers, wire it to Reflex state, and never touch JavaScript. + +### How do I register my Reflex app with Microsoft Entra ID? + +In the Azure Portal, go to App registrations and create a new registration. Set your redirect URIs for local and production environments, generate a client secret under Certificates & secrets, and note your tenant ID and client ID. Reflex uses the authorization code flow since all auth runs server-side. + +### What's the difference between implementing Azure Auth in Reflex versus a React app? + +Reflex handles all auth logic server-side in Python, so client secrets never touch the browser and session management lives in Python state variables. React apps split auth between frontend and backend, requiring separate token storage, expiration handling, and cross-origin configuration. + +### When should I deploy with VPC instead of standard cloud hosting for Azure Auth apps? + +If your organization operates in finance or healthcare, or if compliance requires keeping auth flows inside customer-controlled networks, VPC deployment routes Entra ID integration through private network infrastructure while maintaining the same Python codebase. + +### Does role-based access control work with Microsoft Entra ID groups in Reflex? + +Yes. Group memberships and custom roles from Entra ID appear in the ID token claims, and Reflex reads them into a `user_roles` state variable. You check that list in Python to show or hide admin panels, data views, and protected routes based on role membership. diff --git a/blog/python-web-app-databricks.md b/blog/python-web-app-databricks.md new file mode 100644 index 000000000..0abf18a73 --- /dev/null +++ b/blog/python-web-app-databricks.md @@ -0,0 +1,157 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Databricks in 2026" +title_tag: "Python Web App With Databricks (April 2026)" +description: "Learn how to build a Python web app with Databricks in April 2026. Complete tutorial covering Databricks SDK integration, real-time analytics, and deployment." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Databricks Python app, Databricks web app, Spark Python app, data lakehouse app, Databricks integration Python" + } +] +faq: [ + {"question": "Can I build a web app with Databricks without learning JavaScript?", "answer": "Yes. Reflex lets you build full-stack web apps connected to Databricks entirely in Python—no JavaScript required. You write Databricks queries in Python event handlers, bind results to UI components, and deploy without touching React or maintaining separate frontend/backend codebases."}, + {"question": "Databricks SDK vs Databricks SQL Connector for web dashboards?", "answer": "The Databricks SQL Connector is the right choice for most analytics dashboards, delivering sub-second query latency for direct warehouse queries. The Databricks SDK becomes useful when your app needs to manage clusters, trigger jobs, or automate pipelines beyond pure data retrieval."}, + {"question": "How do I query Databricks data from a Reflex app?", "answer": "Install the Databricks SDK via pip, configure your workspace URL and access token as environment variables, then instantiate the `WorkspaceClient` inside a Reflex state class. Run queries within event handlers and assign results to state variables—components bound to those variables re-render automatically when data updates."}, + {"question": "What's the best way to deploy a Databricks dashboard in 2026?", "answer": "Reflex Cloud handles deployment with a single command, automatically provisioning infrastructure and managing secrets for Databricks credentials. For regulated industries or private VPC setups, Reflex supports hybrid architectures where the frontend deploys to Reflex Cloud while the Python backend runs inside your own security perimeter."}, + {"question": "When should I switch from Streamlit for Databricks dashboards?", "answer": "Switch when you need event-driven interactions that don't rerun the entire script, server-push updates for real-time data, or production-ready UI customization beyond basic layouts. Reflex's WebSocket-based state sync matches Databricks Structured Streaming's five-millisecond latency, while Streamlit's script rerun model causes performance issues under load."}, + {"question": "How does Reflex handle real-time data updates from Databricks?", "answer": "Reflex uses WebSocket-based state sync to push updates from the server to the browser without client polling. You can pair this with background tasks that run periodic Databricks queries on a schedule, with the UI automatically re-rendering when state variables update."}, + {"question": "What components does Reflex provide for building Databricks dashboards?", "answer": "Reflex ships 60+ built-in components covering charts, tables, forms, and layout primitives, all configurable in Python. This includes data tables, time-series charts, summary cards for KPIs, and interactive filter controls without requiring custom frontend work."}, + {"question": "Can I use Reflex with Databricks in a private VPC?", "answer": "Yes. Reflex supports hybrid architectures where the frontend deploys to Reflex Cloud while the Python backend runs inside your own security perimeter or private VPC. Your frontend connects to any backend URL you specify, keeping private Databricks endpoints private."}, + {"question": "How do I handle authentication for Databricks in a Reflex app?", "answer": "Store your Databricks workspace URL, access token, and cluster ID as environment variables. The Databricks SDK's unified authentication flow picks them up automatically, and Reflex Cloud's secrets management handles these credentials in production without exposing them in your codebase."}, + {"question": "What's the latency for Databricks queries in a Reflex dashboard?", "answer": "The Databricks SQL Connector delivers sub-second query latency for simple queries to SQL warehouses. When paired with Databricks Structured Streaming's real-time mode and Reflex's WebSocket-based state sync, end-to-end latency can reach as low as five milliseconds for operational workloads."}, + {"question": "Do I need separate frontend and backend codebases with Reflex and Databricks?", "answer": "No. Reflex lets you write both frontend and backend in pure Python within the same codebase. The same engineer who writes Databricks queries can build the dashboard UI that displays results, eliminating the need for separate teams or technology stacks."}, + {"question": "How do filters and drill-down interactions work in Reflex dashboards?", "answer": "Every filter control maps to an event handler in your Reflex state class. When users interact with filters like date pickers, the handler re-runs the Databricks query with updated parameters and updates state variables, causing bound components to re-render automatically without page reloads."}, + {"question": "Can I monitor performance issues in my Databricks dashboard?", "answer": "Yes. Reflex Cloud provides built-in observability through OpenTelemetry distributed tracing, giving you latency visibility across each query cycle. When a Databricks SQL query slows down your dashboard, trace data points directly to the offending event handler for optimization."}, + {"question": "What types of Databricks operations can I perform from a Reflex app?", "answer": "Beyond running SQL queries, you can use the Databricks SDK to manage clusters, trigger jobs, automate pipeline runs, and handle Delta table reads. The SDK covers all public Databricks REST API operations and integrates directly into Reflex event handlers."}, + {"question": "Who is the target user for a Reflex-Databricks dashboard?", "answer": "The target user is typically a business analyst or operations manager who needs access to Databricks Lakehouse data on demand but won't open a notebook to get it. These users need interactive dashboards with filters and drill-downs that don't require SQL knowledge."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build production Databricks dashboards in pure Python without learning React or JavaScript. + +- Reflex's WebSocket-based state sync delivers sub-second query-to-UI updates for real-time analytics. + +- The Databricks SDK integrates directly into Reflex event handlers with no adapter layer required. + +- Reflex is an open-source Python framework that lets you build full-stack web apps entirely in Python, with 60+ built-in components, AI-powered generation, and enterprise deployment options including VPC and on-premises hosting. + +## Why Python Developers Are Building Web Apps With Databricks in 2026 + +Data teams have always had a Databricks problem. Not with the data itself: the queries run, the pipelines work, the Lakehouse holds everything neatly. The problem is getting that data in front of the people who need it. Building an interactive web interface on top of Databricks historically meant hiring frontend engineers, learning React, and maintaining two separate codebases. For ML engineers and data scientists, that's a wall. + +The [Databricks SDK for Python](https://docs.databricks.com/aws/en/dev-tools/sdk-python) covers all public Databricks REST API operations and accelerates development against the full Lakehouse surface area. That part is clean. But the SDK doesn't give you a UI. And in 2026, shipping a static dashboard or a one-off Streamlit script no longer cuts it for teams running production workflows. + +[Reflex changes the equation entirely](https://reflex.dev/blog/reflex-databricks-partnership/). Because everything (frontend, backend, state management) lives in pure Python, data teams can query Databricks and wire those results directly into interactive components without touching JavaScript. No React. No separate API layer. The same engineer who wrote the Spark query builds the dashboard that displays it. + +## What You'll Build: A Python Web App Powered by Databricks + +The app you'll build here is a real-time analytics dashboard that queries a Databricks SQL warehouse, displays live metrics through interactive charts and filterable tables, and lets business users drill into the data they care about with no SQL required on their end. + +Real-time analytics refers to collecting and analyzing data with minimal latency, where timeliness drives decisions. Think predictive maintenance alerts, demand forecasting, or live business metrics that go stale the moment they stop refreshing. That is exactly what this [Reflex](https://reflex.dev/databricks/) app surfaces. + +The core workflow looks like this: + +- A Databricks SQL warehouse runs queries against your Delta tables, returning structured results that feed directly into your [app's state layer](https://reflex.dev/templates/real-time-sales-dashboard/). + +- Reflex state management holds query results and responds to user interactions, keeping the UI and data in sync without manual wiring. + +- Filter controls, date pickers, and drill-down actions all trigger new queries without a page reload, so the experience feels fast and responsive. + +- Charts and data tables update automatically when state changes, giving users a live view of the metrics they care about. + +What makes Reflex the right fit for this is the component library. Reflex ships 60+ [60+ built-in charts and data components](https://reflex.dev/blog/top-10-data-visualization-libraries/), all configurable in Python. No custom frontend work is needed to make the UI feel production-ready. + +The target user for this kind of app is business users who need Lakehouse data on demand but won't open a notebook to get it. Your job is to close that gap. + +## Connecting Databricks to Your Reflex App + +Reflex treats Databricks like any other Python dependency. There's no plugin system, no special connector to configure through a UI. You install, import, and call. + +### Installing the Databricks SDK + +The [Databricks SDK for Python](https://docs.databricks.com/aws/en/dev-tools/sdk-python) works from both local development machines and within Databricks notebooks. Install it via pip alongside Reflex and it's immediately available across your entire project. Because Reflex runs a real Python backend, any PyPI package you install is callable directly from your event handlers and state classes. No adapter layers required. + +### Configuring Authentication + +Reflex supports project-level integration configuration, so Databricks credentials are set once and shared across every app in the project. Store your workspace URL, access token, and cluster ID as environment variables. The SDK's unified authentication flow picks them up automatically, so you never hardcode credentials or manage config files per app. + +### Querying Data from Event Handlers + +Your state class is where the Databricks connection lives. Instantiate the `WorkspaceClient` inside a state variable or directly within an event handler, run your query, and assign results to a state variable. The moment that variable updates, any component bound to it updates automatically. No manual refresh logic, no polling loop. + +Which integration method you reach for depends on what you're building: + +| Integration Method | Use Case | Latency Profile | +|---|---|---| +| Databricks SQL Connector | Direct SQL queries to warehouses | Sub-second for simple queries | +| Databricks SDK | Cluster management and automation | API call dependent | +| Delta table reads | Batch analytics data | Depends on table size | + +For most analytics dashboards, the SQL Connector is the right default. The SDK becomes useful when your app needs to do more than query, such as spinning up clusters, managing jobs, or triggering pipeline runs as part of the user workflow. + +## Building the UI Around Databricks in Pure Python + +Reflex's component model keeps the UI layer straightforward: state variables flow directly into components, and those components re-render automatically when variables change. + +### Displaying Query Results with Reflex Components + +Query results stored in your state class become the data source for [Reflex data tables](https://reflex.dev/blog/using-ag-grid-in-reflex/) and graphing components without any serialization or prop-drilling. Pass a state variable to a chart or table component, and the binding is live. When the variable updates after a fresh Databricks query, every bound component reflects it instantly with no JavaScript event listeners or manual DOM updates. + +For a metrics dashboard, this typically means summary cards showing aggregated KPIs at the top, a time-series chart below, and a filterable table for row-level inspection. All three pull from the same state class, so they stay in sync. + +### Handling Real-Time Updates + +Reflex uses WebSocket-based state sync, so the server can push updates to the browser without client polling. For Databricks dashboards refreshing against Delta tables, pair this with [background tasks that run scheduled queries](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/). Real-time mode in Databricks Structured Streaming [delivers five-millisecond end-to-end latency](https://docs.databricks.com/aws/en/structured-streaming/real-time) for production workloads like fraud detection. Reflex's push model matches that speed on the UI side. + +### Interactive Filtering and Drill-Down + +Every filter control maps to an event handler in your state class. When a user selects a new date range, the handler re-runs the Databricks query with updated parameters and overwrites the results variable. The table and chart re-render automatically. Unlike Streamlit, event-driven state means only the relevant query reruns, not the entire script, giving users a fast and responsive experience backed by clean, readable Python. + +## Deploying Your Databricks App to Production + +Once your app is ready for production, getting it live is straightforward. The sections below cover deployment options, compliance considerations, and performance monitoring. + +### Single Command Deployment + +[Deploying takes a single command](https://reflex.dev/hosting/) through Reflex Cloud, which handles infrastructure provisioning automatically. Databricks credentials stored as environment variables carry over through Reflex Cloud's secrets management, so your workspace URL and access tokens never touch the codebase. + +### VPC and On-Premises Options for Compliance + +If your Databricks workspace runs inside a private VPC or on-premises environment, Reflex supports hybrid architectures where the frontend deploys to Reflex Cloud while the Python backend runs inside your own security perimeter. Your frontend connects to any backend URL you specify, which keeps private Databricks endpoints private. For teams in compliance-heavy industries, the [on-prem App Builder keeps your stack secure](https://reflex.dev/blog/on-premises-deployment/). + +### Monitoring Query Performance + +Reflex Cloud's built-in observability through OpenTelemetry distributed tracing gives you latency visibility across each query cycle. When a Databricks SQL query starts slowing your dashboard, trace data points directly to the offending event handler. From there, you optimize the query in Databricks, update the state method, and redeploy without touching anything else in the stack. + +## FAQ + +### Can I build a web app with Databricks without learning JavaScript? + +Yes. Reflex lets you build full-stack web apps connected to Databricks entirely in Python, with no JavaScript required. You write Databricks queries in Python event handlers, bind results to UI components, and deploy without touching React or maintaining separate frontend/backend codebases. + +### Databricks SDK vs Databricks SQL Connector for web dashboards? + +The Databricks SQL Connector is the right choice for most analytics dashboards, delivering sub-second query latency for direct warehouse queries. The Databricks SDK becomes useful when your app needs to manage clusters, trigger jobs, or automate pipelines beyond pure data retrieval. + +### How do I query Databricks data from a Reflex app? + +Install the Databricks SDK via pip, configure your workspace URL and access token as environment variables, then instantiate the `WorkspaceClient` inside a Reflex state class. Run queries within event handlers and assign results to state variables. Components bound to those variables re-render automatically when data updates. + +### What's the best way to deploy a Databricks dashboard in 2026? + +Reflex Cloud handles deployment with a single command, automatically provisioning infrastructure and managing secrets for Databricks credentials. For compliance-heavy industries or private VPC setups, Reflex supports hybrid architectures where the frontend deploys to Reflex Cloud while the Python backend runs inside your own security perimeter. + +### When should I switch from Streamlit for Databricks dashboards? + +Switch when you need event-driven interactions that don't rerun the entire script, server-push updates for real-time data, or production-ready UI customization beyond basic layouts. Reflex's WebSocket-based state sync matches Databricks Structured Streaming's five-millisecond latency, while Streamlit's script rerun model causes performance issues under load. diff --git a/blog/python-web-app-epic-ehr.md b/blog/python-web-app-epic-ehr.md new file mode 100644 index 000000000..1bcf9d44d --- /dev/null +++ b/blog/python-web-app-epic-ehr.md @@ -0,0 +1,156 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Epic EHR in 2026" +title_tag: "Build Python Web App With Epic EHR 2026" +description: "Learn to build HIPAA-compliant Python web apps with Epic EHR using FHIR APIs and Reflex framework. Complete integration guide for April 2026." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Epic EHR Python app, FHIR Python web app, healthcare Python app, EHR integration, clinical web app, Epic API Python" + } +] +faq: [ + {"question": "Can I build a Python web app with Epic EHR without JavaScript?", "answer": "Yes. Reflex lets you build full Epic EHR integrations in pure Python, covering both frontend and backend without writing any JavaScript. The same developer who queries Epic's FHIR endpoints builds the clinical interface around it."}, + {"question": "How do I authenticate my Python app with Epic's API?", "answer": "Use OAuth 2.0 with PKCE configured at the project level in Reflex. Your credentials are shared across all apps in that project, and event handlers call Epic's FHIR endpoints directly inside Python state classes without separate API middleware."}, + {"question": "What's the fastest way to pull patient data from Epic into a web app in 2026?", "answer": "Query Epic's FHIR resources (Patient, Observation, MedicationRequest) through Python state classes that map directly to UI components. When clinicians select a patient or adjust filters, event handlers fire the API call, update state, and the interface reflects new data automatically."}, + {"question": "When should I consider deploying an Epic integration app to production?", "answer": "When your app meets Epic's production requirements: OAuth 2.0 with PKCE at the infrastructure level, VPC or on-premises deployment for network isolation, role-based access control matching Epic's permission model, and proper secrets management. Building with these boundaries from the start saves time during Epic's technical review."}, + {"question": "What FHIR resources does Epic provide access to for clinical data?", "answer": "Epic on FHIR provides access to resources including Patient (demographics), Observation (lab results and vital signs), MedicationRequest (prescribed medications), AllergyIntolerance (documented allergies), and Encounter (visit history). Epic offers over 750 no-cost APIs with full USCDI v3 support through open.epic."}, + {"question": "Why is Epic EHR integration important for healthcare developers?", "answer": "Epic holds over 250 million patient records and runs major US health systems like Mayo Clinic, Kaiser Permanente, Johns Hopkins, and Cleveland Clinic. If your clinical tool doesn't integrate with Epic, it's working with incomplete data given Epic's dominant footprint in US healthcare."}, + {"question": "What makes Reflex different from traditional web frameworks for healthcare apps?", "answer": "Reflex is a full-stack Python framework that eliminates the JavaScript barrier, allowing the same developer who writes Epic FHIR queries to build the clinical interface without context switching. It includes 60+ built-in components and handles both frontend and backend in pure Python."}, + {"question": "How does real-time data sync work in a Reflex Epic integration?", "answer": "Reflex uses WebSocket-based state sync where background tasks query Epic's FHIR endpoints on intervals, parse responses into Python objects, and yield state updates that push instantly to every connected browser session without polling hacks."}, + {"question": "What OAuth flow should I use for backend Epic integrations?", "answer": "Use OAuth 2.0's Client Credentials flow for backend service apps where no user login is required and your app authenticates directly as a system. In Reflex, OAuth credentials are configured once at the project level and work across all apps you build."}, + {"question": "Can Epic integrations support wearable device data?", "answer": "Yes. Epic supports wearable device connections for continuous patient monitoring, and the same background task pattern that pulls chart data from FHIR endpoints can surface wearable feeds in your dashboard view."}, + {"question": "What compliance controls are required for production Epic deployments?", "answer": "Production Epic deployments require OAuth 2.0 with PKCE at infrastructure level, VPC or on-premises deployment for network isolation, role-based access control matching Epic's permission model, and proper secrets management through a dedicated secrets store."}, + {"question": "Do I need separate API middleware to call Epic's FHIR endpoints in Reflex?", "answer": "No. Reflex event handlers call Epic's FHIR endpoints directly inside Python state classes without requiring separate API middleware to maintain, simplifying the architecture and reducing moving parts."}, + {"question": "How do FHIR resources map to the UI in a Reflex app?", "answer": "Each FHIR resource maps to a component that reads directly from Reflex state. For example, medication lists render from PatientState.medications and allergy banners from PatientState.allergies. When data updates, the UI reflects changes automatically."}, + {"question": "What infrastructure checks does Epic perform during production app review?", "answer": "Epic's production app review checks for OAuth 2.0 with PKCE configured at infrastructure level, network isolation through VPC or on-premises deployment, role-based access controls aligned with Epic's permission model, and proper secrets management before approving access to live patient data."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- You can build HIPAA-compliant Epic EHR apps in pure Python using Reflex's framework and Epic's FHIR APIs. + +- Epic holds 250M+ patient records across major US health systems, making integration critical for clinical tools. + +- Reflex eliminates the JavaScript barrier between Python data teams and production clinical interfaces. + +- OAuth 2.0 configuration happens once at project level and works across all apps you build on Epic's API. + +- Reflex is a full-stack Python framework that lets healthcare developers build web apps without learning JavaScript. + +## Why Python Developers Are Building Web Apps With Epic EHR in 2026 + +Epic's reach in US healthcare is hard to overstate. The system holds [over 250 million patient records](https://www.tactionsoft.com/blog/epic-ehr-integration-guide/) and runs major health systems like Mayo Clinic, Kaiser Permanente, Johns Hopkins, and Cleveland Clinic. For any developer building clinical tools, that footprint means one thing: if your app doesn't talk to Epic, it's working with incomplete data. + +Python has quietly become the default language for healthcare data science. The same teams querying patient cohorts, training predictive models, and running outcomes research are increasingly the ones tasked with building the internal tools that sit on top of that work. The problem? Getting those Python backends in front of clinicians historically required a full frontend stack, a JavaScript developer, and weeks of glue work. + +That's the bottleneck. Without proper integration, Epic stays a data silo instead of a data hub. Add a JavaScript barrier on top of that, and Python teams end up shipping nothing to production despite having everything they need analytically. + +Reflex removes that last mile. With [pure Python for frontend and backend](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/), the same developer who writes the Epic FHIR query also builds the clinical interface around it, no context switching required. + +## What You'll Build: A Python Web App Powered by Epic EHR + +The app you're building is a patient dashboard that pulls live clinical data from Epic through its FHIR APIs and surfaces it in an interactive Python interface. Think real-time vitals, medication lists, allergy flags, and encounter history, all visible in one place without a nurse having to dig through Epic's native UI. + +Here's what the [architecture covers](https://reflex.dev/use-cases/healthcare/): + +- OAuth 2.0 authentication against Epic's authorization server, handling token exchange and refresh so your app maintains secure access throughout a clinical session + +- FHIR resource queries for patient demographics, medications, allergies, encounters, observations, and vitals + +- A Reflex state class that holds the fetched data and refreshes it on demand + +- A clean clinical UI built entirely in Python using Reflex's 60+ built-in components + +> + +FHIR resources are structured for consistency and interoperability, which means the same query patterns that pull vitals today can pull lab results or imaging orders tomorrow with minimal rework. + +Patient data retrieval is the foundation. Once that pipeline works, medication ordering, appointment scheduling, and care coordination workflows follow the same architectural pattern, so what you build here scales into a full clinical tool. + +## Connecting Epic EHR to Your Reflex App + +Epic's API layer has two main entry points: OAuth 2.0 for authentication and FHIR endpoints for clinical data. Getting these wired into a Reflex app is more straightforward than it sounds. + +### Authentication and API Configuration + +Python developers use [OAuth 2.0's Client Credentials flow](https://www.spritle.com/blog/how-to-integrate-with-epic-ehr-using-python-and-smart-on-fhir-apis/) for [backend service apps](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/), where no user login is required and your app authenticates directly as a system. In Reflex, OAuth credentials are configured at the project level and shared across all apps in that project. One credential setup covers every dashboard, tool, or workflow you build on top of it. From there, Reflex event handlers call Epic's FHIR endpoints directly inside Python state classes, so there's no separate API middleware to maintain. + +### FHIR Resource Access Patterns + +[Epic on FHIR](https://fhir.epic.com/) is a free resource supporting the HL7 FHIR standard, and [open.epic](https://open.epic.com/) gives developers access to over 750 no-cost APIs, including full USCDI v3 support. Each FHIR resource [maps to a Reflex state variable](https://reflex.dev/templates/), which keeps the UI reactive when data refreshes. + +| FHIR Resource | Clinical Data | Access Pattern | Reflex State Mapping | +|---|---|---|---| +| Patient | Demographics, identifiers | Read by FHIR ID | PatientState.demographics | +| Observation | Lab results, vitals | Search by patient + category | PatientState.vitals | +| MedicationRequest | Prescribed medications | Search by patient | PatientState.medications | +| AllergyIntolerance | Documented allergies | Search by patient | PatientState.allergies | +| Encounter | Visit history | Search by patient + date | PatientState.encounters | + +Reflex's component library and app API handle the rest of the wiring between these state classes and the UI. + +## Building the UI Around Epic EHR in Pure Python + +With state classes mapped to FHIR resources, the next step is displaying that clinical data in a usable interface. Reflex's component system handles this entirely in Python, no JavaScript required. + +There are two distinct UI challenges when building against Epic EHR: displaying structured clinical data clearly and keeping that data current as patients are monitored. + +### Patient Data Display Components + +Each FHIR resource maps to a component that reads directly from Reflex state. A medication list displays from `PatientState.medications`, an allergy banner from `PatientState.allergies`, vitals cards from `PatientState.vitals`. When a clinician selects a different patient or adjusts a date range, event handlers fire the corresponding Epic API call, update state, and the UI reflects the new data automatically. + +Python developers who already understand Epic's FHIR SDK [own the entire interface](https://reflex.dev/migration/no-code/). There's no handoff to a frontend team, no separate component library to learn. Reflex's 60+ built-in components cover tables, charts, modals, and data grids out of the box. + +### Real-Time Clinical Data Updates + +Growing demand for real-time data exchange reflects a simple clinical reality: live data underlies successful treatment and recovery. Reflex's WebSocket-based state sync makes this achievable without polling hacks. + +Background tasks query Epic's FHIR endpoints on intervals, parse responses into Python objects, and yield state updates that push instantly to every connected browser session. Epic also supports wearable device connections for continuous patient monitoring, meaning the same background task pattern that pulls chart data can surface wearable feeds in the same dashboard view. + +## Deploying Your Epic EHR App to Production + +[Security and interoperability](https://reflex.dev/blog/enterprise-ready-ai-app-builder/) remain [critical in Epic EHR integrations](https://topflightapps.com/ideas/how-integrate-health-app-with-epic-ehr-emr/), with OAuth 2.0 with PKCE and standardized FHIR endpoints protecting PHI across every request your app makes. + +### Cloud Deployment with Compliance Controls + +Getting a HIPAA-compliant app into production involves more than writing good code. You need infrastructure that respects data sovereignty, network isolation, and access controls that map cleanly onto clinical roles. + +Key deployment considerations for Epic-connected apps include: + +- OAuth 2.0 with PKCE must be configured at the infrastructure level, beyond application code alone, so credentials are never exposed through environment leakage or hardcoded config. + +- VPC and [on-premises deployment options](https://reflex.dev/blog/on-premises-deployment/) let health systems keep patient data within defined network boundaries, which many enterprise Epic customers require before granting production API access. + +- Role-based access control (RBAC) restricts which authenticated users can query specific patient records, keeping your app aligned with Epic's own permission model. + +- Secrets management should be handled through a dedicated secrets store so API credentials propagate consistently across every service in your project without manual intervention. + +These controls matter because Epic's production app review process checks for exactly this kind of [infrastructure discipline](https://reflex.dev/hosting/) before approving access to live patient data. Building with these boundaries from the start, instead of retrofitting them before launch, saves substantial time during Epic's technical review and reduces the risk of a failed certification cycle. + +## FAQ + +### Can I build a Python web app with Epic EHR without JavaScript? + +Yes. Reflex lets you build full Epic EHR integrations in pure Python, covering both frontend and backend without writing any JavaScript. The same developer who queries Epic's FHIR endpoints builds the clinical interface around it. + +### How do I authenticate my Python app with Epic's API? + +Use OAuth 2.0 with PKCE configured at the project level in Reflex. Your credentials are shared across all apps in that project, and event handlers call Epic's FHIR endpoints directly inside Python state classes without separate API middleware. + +### What's the fastest way to pull patient data from Epic into a web app in 2026? + +Query Epic's FHIR resources (Patient, Observation, MedicationRequest) through Python state classes that map directly to UI components. When clinicians select a patient or adjust filters, event handlers fire the API call, update state, and the interface reflects new data automatically. + +### When should I consider deploying an Epic integration app to production? + +When your app meets Epic's production requirements: OAuth 2.0 with PKCE at the infrastructure level, VPC or on-premises deployment for network isolation, role-based access control matching Epic's permission model, and proper secrets management. Building with these boundaries from the start saves time during Epic's technical review. diff --git a/blog/python-web-app-with-perplexity.md b/blog/python-web-app-with-perplexity.md new file mode 100644 index 000000000..86ef1acf3 --- /dev/null +++ b/blog/python-web-app-with-perplexity.md @@ -0,0 +1,139 @@ +--- +author: Tom Gotsman +date: 2026-04-06 +title: "How to Build a Python Web App With Perplexity in 2026" +title_tag: "Build Python Web App With Perplexity 2026" +description: "Learn how to build a Python web app with Perplexity API in April 2026. Full tutorial covering real-time streaming, citations, and deployment without JavaScript." +show_in_cards: false +tag: Builder +meta: [ + { + "name": "keywords", + "content": "Perplexity Python app, Perplexity API web app, AI search Python app, Perplexity integration, research app Python" + } +] +faq: [ + {"question": "Can I build a web app with Perplexity without learning JavaScript?", "answer": "Yes. Reflex lets you build the entire app—frontend, backend, and Perplexity integration—in pure Python. You connect the Perplexity SDK through async event handlers and stream responses directly to UI components without touching JavaScript, React, or any frontend framework."}, + {"question": "Perplexity API vs OpenAI API for building search apps?", "answer": "Perplexity combines LLM reasoning with live web search and returns cited sources, solving the stale training data problem. OpenAI's API (including gpt-5.4) doesn't include built-in web search or citations, so you'd need to build that layer yourself with a separate search service and custom citation parsing."}, + {"question": "How do I stream Perplexity responses in real-time to users?", "answer": "Reflex's WebSocket-based state sync handles this automatically. Your async event handler iterates over Perplexity's streaming response, updates a state variable with each token, and Reflex pushes every change to the browser instantly—no manual polling or JavaScript event handling required."}, + {"question": "What's the fastest way to deploy a Python web app with API integrations in 2026?", "answer": "Write your app in Reflex, set API keys as project-level secrets, then run `reflex deploy`. The command provisions infrastructure, manages HTTPS, and handles environment variables automatically. For apps using services like Perplexity, this typically takes under 10 minutes from working code to production URL."}, + {"question": "How does Perplexity's API handle citations and source verification?", "answer": "Perplexity's API returns cited sources alongside its answers, allowing your app to display, link to, or process them further. The SDK provides citations at the end of the streaming response, which you can map to UI components like links, giving users a direct way to verify information or explore sources in depth."}, + {"question": "What are the main components needed for a Perplexity-powered research app?", "answer": "You need a query input for user questions, a response stream to display AI answers in real-time, a citation list to show source links, and follow-up suggestions to present related questions. Reflex handles all of these as Python components that bind directly to your state variables."}, + {"question": "Can I maintain conversation context across multiple queries with Perplexity?", "answer": "Yes. The app supports multi-turn conversations, allowing users to ask follow-up questions without losing context. You maintain conversation history in your state class, and Perplexity's API processes subsequent queries with awareness of the prior exchange."}, + {"question": "How do I manage API keys securely when deploying a Perplexity app?", "answer": "Set your PERPLEXITY_API_KEY as a project-level secret in Reflex Cloud, which propagates across all deployed apps without exposing credentials in source code or version control. The Perplexity Python client automatically reads this environment variable, and you can rotate keys by updating one setting rather than modifying individual app files."}, + {"question": "What's the difference between polling and Reflex's WebSocket state sync for streaming?", "answer": "Reflex's WebSocket layer automatically pushes state changes to the browser as they occur, eliminating the need for polling or manual serialization. When your event handler updates a state variable with each streamed token from Perplexity, Reflex re-renders the relevant components instantly, making responses feel native rather than batched."}, + {"question": "Can I use Perplexity's API in regulated industries or on-premises deployments?", "answer": "Yes. Reflex supports self-hosted and VPC deployment options as compliance-ready alternatives to cloud hosting. You can deploy your Perplexity-powered app in controlled environments while still leveraging Reflex's full-stack Python framework and built-in deployment tooling."}, + {"question": "How do I prevent unexpected API costs when running a Perplexity app in production?", "answer": "Use rate limiting in your event handlers to control request volumes, and set usage alerts in Reflex Cloud to catch cost spikes early. Perplexity uses pay-as-you-go pricing with no monthly minimums, so controlling the frequency of API calls keeps production costs predictable."}, + {"question": "What performance benefits does Perplexity provide for research teams?", "answer": "According to Perplexity, companies using its API save 8 hours of research per rep per week, leading to a 20% increase in throughput. This comes from wiring real-time search with cited sources directly into workflows, eliminating manual research and verification steps."}, + {"question": "Do I need separate frontend and backend developers to build a Perplexity app?", "answer": "No. Reflex lets you write the entire application in Python, including the frontend, backend, and API integration. This eliminates the need for JavaScript expertise or a separate frontend team, allowing Python developers to build complete web apps without context switching between languages."}, + {"question": "How does Perplexity solve the stale training data problem?", "answer": "Perplexity combines LLM reasoning with live web search, returning answers based on current information rather than months-old training data. Every response includes cited sources, giving users a way to verify that the information reflects recent developments rather than outdated model knowledge."} +] +--- + +```python exec +import reflex as rx +from pcweb.components.image_zoom import image_zoom +``` + +**TLDR:** + +- Perplexity's API provides live web search with cited sources, saving research teams 8 hours per rep per week + +- Reflex lets you build the full web app in Python: frontend, backend, and streaming responses, all without JavaScript + +- Stream real-time answers and citations using Reflex's WebSocket state sync paired with Perplexity's Python SDK + +- Deploy with `reflex deploy` and manage API keys at the project level for secure, production-ready apps + +- Reflex builds full-stack Python web apps without JavaScript, used by 40% of Fortune 500 companies for internal tools + +## Why Python Developers Are Building Web Apps With Perplexity in 2026 + +Most AI apps hit the same wall: the model's training data is months old. You get confident answers about things that changed last quarter, and no citations to verify anything. For Python developers building research tools, internal knowledge bases, or customer-facing search products, this is a real problem. + +Perplexity's API solves this directly. It combines LLM reasoning with live web search, returning answers with cited sources your app can display, link to, or process further. According to Perplexity, companies using its API [save 8 hours](https://docs.perplexity.ai/) of research per rep per week, leading to a 20% increase in throughput. That's a production result from wiring real-time search into an actual workflow. + +> + +Perplexity's API is built for running agentic workflows across frontier models with built-in web search, URL fetching, and reasoning controls, making it one of the fastest ways to add grounded, cited AI responses to any application. + +The missing piece for most Python developers is the frontend. Calling an API is straightforward. Building a full web app around it, with state, routing, real-time UI updates, and deployment, typically means learning React or hiring someone who knows it. + +That's where Reflex comes in. With Reflex, you [write your entire app in Python](https://reflex.dev/blog/how-to-build-python-web-app-complete-tutorial/), frontend included. No JavaScript, no separate frontend team, no context switching between languages. + +## What You'll Build: A Python Web App Powered by Perplexity + +Before writing any code, it helps to see the full picture. What you're building is a [real-time research assistant](https://reflex.dev/templates/chat-bot/): users type a question, Perplexity's Sonar API fetches live web data, and the app streams back a grounded answer with source citations. Think of it as a search-augmented chat interface that stays current without any manual data pipeline. + +The app handles [multi-turn conversations](https://reflex.dev/templates/knowledge-chat/), so users can ask follow-up questions without losing context. Every response shows citations inline, giving readers a way to verify sources or dig deeper. Perplexity's API also returns related questions, which you can surface as clickable suggestions to keep users in the flow. + +| Component | Purpose | Perplexity Feature Used | +|---|---|---| +| Query Input | User enters search questions | Sonar API request | +| Response Stream | Display AI answers in real-time | WebSocket state updates | +| Citation List | Show source links for verification | Citations from API response | +| Follow-up Suggestions | Present related questions | Related questions feature | + +The Perplexity Python SDK supports [full streaming via server-sent events](https://reflex.dev/blog/unlocking-new-workflows-with-background-tasks/), and its OpenAI-compatible format means the integration is straightforward. Reflex's WebSocket-based state sync pairs naturally with streaming responses, pushing each token to the UI as it arrives. + +## Connecting Perplexity to Your Reflex App + +Start by installing the SDK with `pip install perplexity-python`, then add your API key to your environment. The [Perplexity Python client](https://docs.perplexity.ai/docs/sdk/overview) automatically reads `PERPLEXITY_API_KEY` from your environment or a `.env` file via python-dotenv. Configure credentials once at the project level and share them across every app in that project, eliminating hardcoded keys and redundant setup across environments. + +### Setting Up API Authentication + +Inside your Reflex app, define your state class as a normal Python class. API credentials load from environment variables through Reflex's config layer, keeping secrets out of source code. Because Reflex manages integrations at the project level, rotating a key or swapping environments requires changing one setting, not hunting through individual app files. + +### Calling Perplexity from Event Handlers + +Event handlers are where the API call lives. An async handler calls the Perplexity SDK, iterates over streamed tokens, and updates a state variable on each chunk. Because Reflex's WebSocket layer watches for state changes, each update pushes directly to the UI. No polling, no manual serialization, no JavaScript involved. This makes real-time AI responses feel native to your app instead of bolted on after the fact. + +## Building the UI Around Perplexity in Pure Python + +With the API wired up, the next step is building the interface that users actually interact with. Reflex's [component library](https://reflex.dev/blog/custom-components/) covers everything you need for a search app: inputs, buttons, text display, loading indicators, and links. All of it in pure Python. + +### State Variables and Response Handling + +Your state class holds everything the UI needs to know. A `query_text` string captures what the user typed. A `response_content` string accumulates streamed tokens. A `citations` list stores source URLs returned by Perplexity. An `is_loading` boolean drives the spinner, and an `error_message` string handles edge cases. When any of these variables change, Reflex updates the relevant components automatically, no manual DOM manipulation required. This reactive approach makes streaming feel instant instead of batched. + +### Streaming Response Integration + +As tokens arrive from Perplexity's SDK via async iteration, each chunk appends to `response_content`. Reflex pushes every state change to the browser over WebSocket, so the answer display updates token by token, matching the experience users expect from interfaces like ChatGPT. Citations arrive at the end of the stream and populate the `citations` list, which maps to `rx.link` components with proper href attributes. Related questions render as buttons bound to the same search handler, letting users ask follow-ups without retyping. The styling layer handles layout and spacing entirely through Python keyword arguments. + +| UI Element | Reflex Component | Bound State Variable | +|---|---|---| +| Search input | rx.input | query_text | +| Submit button | rx.button | on_click handler | +| Answer display | rx.text_area | response_content | +| Citation links | rx.link | citations list | +| Loading indicator | rx.spinner | is_loading boolean | + +## Deploying Your Perplexity App to Production + +Running ``[reflex deploy](https://reflex.dev/hosting/) from your project root handles the full deployment process automatically. Reflex Cloud provisions infrastructure, manages HTTPS, and supports custom domains out of the box. + +### Secrets Management and Environment Configuration + +Set your `PERPLEXITY_API_KEY` as a project-level secret in Reflex Cloud. It propagates across every deployed app without touching source code or version control. + +### Monitoring API Usage and Performance + +[Reflex Cloud's built-in metrics](https://reflex.dev/blog/self-hosting-reflex-with-docker/) track request volumes and error rates. Set usage alerts to catch cost spikes early. Perplexity uses [pay-as-you-go pricing with no monthly minimums](https://popularaitools.ai/blog/perplexity-api-review-2026), so rate limiting your event handlers keeps production costs predictable. For compliance-focused industries, Reflex supports [self-hosted and VPC deployment](https://reflex.dev/blog/on-premises-deployment/) as compliance-ready alternatives. + +## FAQ + +### Can I build a web app with Perplexity without learning JavaScript? + +Yes. Reflex lets you build the entire app (frontend, backend, and Perplexity integration) in pure Python. You connect the Perplexity SDK through async event handlers and stream responses directly to UI components without touching JavaScript, React, or any frontend framework. + +### Perplexity API vs OpenAI API for building search apps? + +Perplexity combines LLM reasoning with live web search and returns cited sources, solving the stale training data problem. OpenAI's API (including gpt-5.4) doesn't include built-in web search or citations, so you'd need to build that layer yourself with a separate search service and custom citation parsing. + +### How do I stream Perplexity responses in real-time to users? + +Reflex's WebSocket-based state sync handles this automatically. Your async event handler iterates over Perplexity's streaming response, updates a state variable with each token, and Reflex pushes every change to the browser instantly. No manual polling or JavaScript event handling required. + +### What's the fastest way to deploy a Python web app with API integrations in 2026? + +Write your app in Reflex, set API keys as project-level secrets, then run `reflex deploy`. The command provisions infrastructure, manages HTTPS, and handles environment variables automatically. For apps using services like Perplexity, this typically takes under 10 minutes from working code to production URL. From cd66bb899e050e235cc29c4670643a9781dce7dc Mon Sep 17 00:00:00 2001 From: Tom Gotsman Date: Tue, 7 Apr 2026 10:33:31 -0700 Subject: [PATCH 3/3] image fix --- pcweb/meta/meta.py | 24 ++++++++++++++---------- pcweb/pages/blog/blog.py | 4 ++-- pcweb/pages/blog/page.py | 2 +- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/pcweb/meta/meta.py b/pcweb/meta/meta.py index 5727374ea..8673d6910 100644 --- a/pcweb/meta/meta.py +++ b/pcweb/meta/meta.py @@ -26,7 +26,7 @@ def _build_meta_tags( title: str, description: str, - image: str, + image: str | None, url: str = REFLEX_DOMAIN_URL, ) -> list[dict[str, str]]: """Build a list of meta tags with the given parameters. @@ -34,13 +34,13 @@ def _build_meta_tags( Args: title: The page title. description: The page description. - image: The image path for social media previews. + image: The image path for social media previews (None to omit). url: The page URL (defaults to REFLEX_DOMAIN_URL). Returns: A list of meta tag dictionaries. """ - return [ + tags = [ # HTML Meta Tags {"name": "application-name", "content": APPLICATION_NAME}, {"name": "description", "content": description}, @@ -49,16 +49,18 @@ def _build_meta_tags( {"property": "og:type", "content": OG_TYPE}, {"property": "og:title", "content": title}, {"property": "og:description", "content": description}, - {"property": "og:image", "content": image}, # Twitter Meta Tags {"name": "twitter:card", "content": TWITTER_CARD_TYPE}, {"property": "twitter:domain", "content": REFLEX_DOMAIN}, {"property": "twitter:url", "content": url}, {"name": "twitter:title", "content": title}, {"name": "twitter:description", "content": description}, - {"name": "twitter:image", "content": image}, {"name": "twitter:creator", "content": TWITTER_CREATOR}, ] + if image: + tags.append({"property": "og:image", "content": image}) + tags.append({"name": "twitter:image", "content": image}) + return tags meta_tags = _build_meta_tags( @@ -105,21 +107,21 @@ def to_cdn_image_url(image: str | None) -> str: def create_meta_tags( - title: str, description: str, image: str, url: str | None = None + title: str, description: str, image: str | None, url: str | None = None ) -> list[rx.Component]: """Create meta tags for a page. Args: title: The page title. description: The page description. - image: The image path for social media previews. + image: The image path for social media previews (None to omit). url: The page URL (optional, defaults to REFLEX_DOMAIN_URL). Returns: A list of meta tag dictionaries. """ page_url = url if url else REFLEX_DOMAIN_URL - image_url = to_cdn_image_url(image) if image else "" + image_url = to_cdn_image_url(image) if image else None return [ *_build_meta_tags( @@ -137,7 +139,7 @@ def blog_jsonld( description: str, author: str, date: str, - image: str, + image: str | None, url: str, faq: list[dict[str, str]] | None = None, author_bio: str | None = None, @@ -154,15 +156,17 @@ def blog_jsonld( if author_bio: author_node["description"] = author_bio + image_url = to_cdn_image_url(image) if image else None posting: dict = { "@type": "BlogPosting", "headline": title, "description": description, - "image": to_cdn_image_url(image), "datePublished": str(date), "url": url, "author": author_node, } + if image_url: + posting["image"] = image_url if updated_at: posting["dateModified"] = str(updated_at) if word_count: diff --git a/pcweb/pages/blog/blog.py b/pcweb/pages/blog/blog.py index 73ad38539..209beffc9 100644 --- a/pcweb/pages/blog/blog.py +++ b/pcweb/pages/blog/blog.py @@ -227,11 +227,11 @@ def blogs(): path=route, title=seo_title, description=document.metadata["description"], - image=document.metadata.get("image", ""), + image=document.metadata.get("image") or None, meta=create_meta_tags( title=seo_title, description=document.metadata["description"], - image=document.metadata.get("image", ""), + image=document.metadata.get("image") or None, url=f"https://reflex.dev{route}", ), )(lambda doc=document, route=route: page(doc, route)) diff --git a/pcweb/pages/blog/page.py b/pcweb/pages/blog/page.py index 0aa9afb6e..deaa545a2 100644 --- a/pcweb/pages/blog/page.py +++ b/pcweb/pages/blog/page.py @@ -206,7 +206,7 @@ def page(document, route) -> rx.Component: description=meta["description"], author=meta["author"], date=str(meta["date"]), - image=meta.get("image", ""), + image=meta.get("image") or None, url=page_url, faq=meta.get("faq"), author_bio=meta.get("author_bio"),