Use PyCharm alongside Retool by developing Python backend services (Flask, FastAPI, Django) in PyCharm that expose REST API endpoints, then connecting those endpoints to Retool as REST API Resources. PyCharm's HTTP client and debugger let you test APIs before Retool consumes them, creating a clean separation between Python data processing logic and Retool's visual dashboard layer.
| Fact | Value |
|---|---|
| Tool | PyCharm |
| Category | DevOps |
| Method | Development Workflow |
| Difficulty | Intermediate |
| Time required | 45 minutes |
| Last updated | April 2026 |
Develop Python Backend Services for Retool Using PyCharm
Retool's visual query builder excels at building UIs on top of existing APIs and databases, but some data processing tasks require custom Python logic — complex aggregations, machine learning model inference, proprietary data transformations, or integrations with Python-only libraries like pandas, numpy, or scikit-learn. PyCharm is the standard tool for developing these Python backend services, and the integration pattern is straightforward: you build and test Python REST APIs in PyCharm, then expose those APIs as Retool REST API Resources.
This pattern is especially common for data engineering teams who have Python-based ETL pipelines and want to expose processed data to operations teams through Retool dashboards. Instead of rewriting Python logic in Retool's JavaScript transformers, you keep the computation in Python where it belongs and expose clean, Retool-friendly JSON endpoints that return exactly the data shape your Retool components need.
PyCharm's integrated HTTP client (under the Tools menu) lets you write and run HTTP requests against your locally running Flask or FastAPI service before deploying to production. This makes it easy to test endpoint responses and verify the JSON structure matches what your Retool app expects, catching issues before they affect the live dashboard.
Integration method
PyCharm and Retool integrate through a development workflow rather than a direct API connection. You write Python backend services in PyCharm using Flask, FastAPI, or Django — these services expose REST endpoints that process data, handle business logic, or connect to databases that Retool can't access directly. Once deployed, these endpoints become Retool REST API Resources. PyCharm's HTTP client lets you test endpoints in development before wiring them to Retool, ensuring a smooth integration workflow.
Prerequisites
- PyCharm Professional or Community Edition installed (Professional recommended for database tools and HTTP client)
- Python 3.8+ with pip installed
- A Python web framework installed: Flask (pip install flask) or FastAPI (pip install fastapi uvicorn)
- A Retool account with permission to create Resources
- A deployment target for your Python service (AWS EC2, Google Cloud Run, Railway, Render, or any server Retool Cloud can reach)
Step-by-step guide
Create a Python REST API service in PyCharm
Open PyCharm and create a new Python project (File → New Project). Choose your preferred framework — FastAPI for modern async APIs or Flask for simpler synchronous services. For a FastAPI project, open the integrated terminal (View → Tool Windows → Terminal) and install dependencies: pip install fastapi uvicorn pydantic. Create a file named main.py with your API service. Design your endpoints with Retool in mind — return flat JSON arrays for Table data, nested objects for detail views, and include pagination metadata (total, page, per_page) for large datasets. Retool binds to {{ query.data }} directly, so your JSON structure determines how easy the Retool wiring is. For a data endpoint that will power a Retool Table, return a JSON object with a 'results' array at the top level: Enable CORS in your Python service for local development (Retool Cloud proxies requests server-side, so CORS isn't needed in production, but may be helpful for local testing with Retool's development environment). Run the service in PyCharm using the Run button (Shift+F10) or the terminal: uvicorn main:app --reload for FastAPI. Your service will be available at http://localhost:8000. For Flask, the equivalent is: flask run (with FLASK_APP=main.py set) or python main.py. The service runs at http://localhost:5000.
1# FastAPI service example — designed for Retool consumption2from fastapi import FastAPI, Query3from fastapi.middleware.cors import CORSMiddleware4from typing import Optional5import pandas as pd6from datetime import datetime78app = FastAPI(title="Retool Data Service")910# CORS for local development (Retool proxies in production)11app.add_middleware(12 CORSMiddleware,13 allow_origins=["*"],14 allow_methods=["*"],15 allow_headers=["*"],16)1718@app.get("/api/sales-summary")19async def get_sales_summary(20 start_date: str = Query(default="2024-01-01"),21 end_date: str = Query(default="2024-12-31"),22 region: Optional[str] = Query(default=None)23):24 # Example: load from database or file25 # Replace with your actual data source26 df = pd.read_sql("SELECT * FROM sales WHERE date >= %s AND date <= %s",27 con=get_db_connection(),28 params=[start_date, end_date])2930 if region:31 df = df[df['region'] == region]3233 summary = df.groupby('product').agg(34 total_revenue=('amount', 'sum'),35 order_count=('order_id', 'count'),36 avg_order=('amount', 'mean')37 ).reset_index()3839 return {40 "results": summary.to_dict(orient='records'),41 "total": len(summary),42 "generated_at": datetime.now().isoformat()43 }Pro tip: Design your FastAPI response schemas explicitly using Pydantic models. This gives you automatic API documentation at http://localhost:8000/docs (Swagger UI) that you can share with your team to document what each endpoint returns — useful for Retool developers writing the frontend queries.
Expected result: The FastAPI service runs on localhost:8000 and returns JSON from your endpoints. The Swagger UI at /docs shows all available endpoints with their request parameters and response schemas.
Test Python endpoints with PyCharm's HTTP client
Before connecting your Python service to Retool, use PyCharm's built-in HTTP client to verify endpoint behavior. This catches response format issues before they become Retool debugging problems. Open the HTTP client in PyCharm: go to Tools → HTTP Client → Create Request or press Ctrl+Alt+Shift+Insert (macOS: Cmd+Option+Shift+Insert). A .http file opens in the editor where you write HTTP requests. Write test requests for each endpoint you plan to connect to Retool: PyCharm executes the request when you click the green Run button next to it and displays the response in the Run panel. You can see the full response JSON, HTTP status code, headers, and response time — exactly the information you need to verify the response structure Retool will receive. For endpoints that require authentication, add an Authorization header in the .http file. PyCharm's HTTP client supports environment files (.env.http) for storing API keys and base URLs that can be referenced as {{ENV_VARIABLE}} in requests — keeping credentials out of the test files. Verify your responses match what Retool expects: arrays of objects for Table data, flat key-value objects for stat displays, or time-series arrays for Chart data. If the response structure doesn't match, fix it in Python now rather than after wiring to Retool.
1### Test sales summary endpoint2GET http://localhost:8000/api/sales-summary3 ?start_date=2024-01-014 &end_date=2024-03-315 ®ion=West6Content-Type: application/json7Authorization: Bearer {{API_KEY}}89###1011### Test endpoint that Retool will use for Table data12GET http://localhost:8000/api/orders13 ?status=pending14 &page=115 &per_page=5016Content-Type: application/json1718###1920### Test POST endpoint for Retool action buttons21POST http://localhost:8000/api/orders/123/process22Content-Type: application/json23Authorization: Bearer {{API_KEY}}2425{26 "action": "approve",27 "notes": "Approved via Retool",28 "operator": "ops-team@company.com"29}Pro tip: PyCharm Professional's HTTP client supports JavaScript test scripts that run after requests complete, letting you assert response structure automatically. Add assertions like client.test('Has results array', () => client.assert.responseBody.results instanceof Array) to catch response format regressions before they affect Retool.
Expected result: Each HTTP request in PyCharm returns a 200 response with the expected JSON structure. The response JSON is displayed in the Run panel and matches the format your Retool queries will consume.
Add authentication to your Python service for Retool
Since Retool proxies all API requests server-side, your Python service needs to authenticate Retool's server-side requests without requiring browser-based OAuth flows. API key authentication is the simplest and most appropriate pattern for Retool-consumed Python services. Implement API key authentication in FastAPI using a dependency: In Flask, implement authentication using a decorator or before_request hook. Generate a secure API key: open PyCharm's terminal and run: python -c "import secrets; print(secrets.token_urlsafe(32))". Store this key in your Python service's environment variables (use python-dotenv in development) and in Retool's configuration variables. For production deployments, never hardcode the API key in your Python source code. Use environment variables and load them with os.environ.get('RETOOL_API_KEY'). PyCharm supports .env file loading with the EnvFile plugin, making it easy to manage environment variables across development and production configurations. Once deployed, configure Retool to send the API key in a header: in the REST API Resource settings, add a default header with key = X-API-Key and value = {{ retoolContext.configVars.PYTHON_SERVICE_API_KEY }}.
1# FastAPI API key authentication dependency2from fastapi import Security, HTTPException, status3from fastapi.security.api_key import APIKeyHeader4import os56API_KEY = os.environ.get('RETOOL_API_KEY')7api_key_header = APIKeyHeader(name='X-API-Key', auto_error=False)89async def get_api_key(api_key: str = Security(api_key_header)):10 if not api_key or api_key != API_KEY:11 raise HTTPException(12 status_code=status.HTTP_401_UNAUTHORIZED,13 detail='Invalid or missing API key'14 )15 return api_key1617# Apply to protected endpoints18@app.get("/api/sales-summary")19async def get_sales_summary(20 start_date: str = Query(default="2024-01-01"),21 end_date: str = Query(default="2024-12-31"),22 _: str = Security(get_api_key) # Requires valid API key23):24 # ... endpoint logicPro tip: For Retool-consumed Python services, keep authentication simple — API key auth in a header is sufficient since Retool proxies all requests server-side. Avoid OAuth 2.0 with user-specific tokens for service-to-service calls; those are appropriate for user-delegated access, not internal service authentication.
Expected result: The Python service rejects requests without a valid X-API-Key header with a 401 response. Requests with the correct API key proceed normally. The PyCharm HTTP client tests confirm the authentication is working before Retool integration.
Deploy the Python service and configure a Retool Resource
Once your Python service is tested locally via PyCharm's HTTP client, deploy it to a server Retool Cloud can reach. Choose a deployment platform based on your infrastructure: - **Railway or Render**: easiest for small services, just push to Git and Railway/Render builds and deploys automatically. Good for Flask/FastAPI services with moderate traffic. - **Google Cloud Run**: serverless containers, excellent for FastAPI services that have bursty traffic and should scale to zero when idle. - **AWS EC2 with nginx**: full control, appropriate for services that need specific networking, VPC placement, or performance requirements. For Railway deployment, create a Procfile in your PyCharm project root: web: uvicorn main:app --host 0.0.0.0 --port $PORT. Push to GitHub and connect to Railway — it detects Python and deploys automatically. Set environment variables (RETOOL_API_KEY) in Railway's environment settings panel. After deployment, note your service's public URL (e.g., https://my-service.railway.app). Go to Retool's Resources tab → Add Resource → REST API. Name it 'Python Data Service'. Set Base URL to your deployed service's URL. Add the API key header: key = X-API-Key, value = {{ retoolContext.configVars.PYTHON_SERVICE_API_KEY }}. Create your first Retool query targeting this resource — set Method to GET, Path to /api/sales-summary, and add URL parameters matching your endpoint's query parameters. Click Run to verify the response and ensure Retool can reach your deployed Python service. For complex data pipelines involving multiple Python services with shared authentication, RapidDev's team can help design the right Retool resource architecture for multi-service backends.
1# Procfile for Railway/Render deployment2web: uvicorn main:app --host 0.0.0.0 --port $PORT34# requirements.txt5fastapi==0.109.06uvicorn[standard]==0.27.07pandas==2.2.08pydantic==2.6.09python-dotenv==1.0.010sqlalchemy==2.0.25Pro tip: For self-hosted Retool, your Python service can run inside the same VPC without a public URL — use internal DNS names or private IP addresses for the Resource base URL. This is more secure than exposing the service publicly and avoids the need for API key authentication entirely when network-level security is sufficient.
Expected result: The Python service is accessible at a public URL. The Retool REST API Resource is configured with the correct base URL and API key header. A test query in Retool returns data from the Python service successfully.
Wire Python endpoints to Retool components and debug with PyCharm
With the Retool resource configured, build queries for each endpoint and bind them to Retool components. For a sales summary dashboard, create a query named getSalesSummary, set Method to GET, Path to /api/sales-summary, and add URL parameters that map Retool component values to your endpoint's query parameters: - start_date: {{ dateRange.start }} - end_date: {{ dateRange.end }} - region: {{ dropdown_region.value || '' }} Bind the query to a Table component: Data = {{ getSalesSummary.data.results }}. Bind a Stat component to show total records: {{ getSalesSummary.data.total }}. For debugging issues between PyCharm-developed code and Retool, use a two-track approach. In PyCharm: attach the debugger (Shift+F9) to your running FastAPI process and set breakpoints in the endpoint function to inspect what data is being computed and returned. In Retool: use the query's Response tab to inspect the raw JSON Retool receives and compare it to PyCharm's debugger output. For request/response mismatches — Retool sending different parameter formats than your Python endpoint expects — add request logging in your FastAPI service to see exactly what Retool sends: This combination of PyCharm debugging and Retool's query inspector covers the full request lifecycle, making it straightforward to trace issues from the Retool UI component through the query parameter, into the Python endpoint, and back to the Retool response binding.
1# Add request logging middleware to FastAPI for debugging Retool integration2import logging3from fastapi import Request4import time56logging.basicConfig(level=logging.INFO)7logger = logging.getLogger(__name__)89@app.middleware("http")10async def log_requests(request: Request, call_next):11 start_time = time.time()12 logger.info(f"Incoming: {request.method} {request.url}")13 logger.info(f"Headers: {dict(request.headers)}")1415 # Log query params (useful for debugging Retool URL parameter issues)16 if request.query_params:17 logger.info(f"Query params: {dict(request.query_params)}")1819 response = await call_next(request)20 process_time = time.time() - start_time21 logger.info(f"Response: {response.status_code} in {process_time:.3f}s")22 return responsePro tip: When Retool sends unexpected parameter formats to your Python service (e.g., date strings vs. date objects, integer vs. string types), add Pydantic validators in FastAPI to coerce and validate incoming parameters. This makes your endpoint resilient to different Retool component value types without requiring exact match.
Expected result: The getSalesSummary query returns data from the Python service and populates the Retool Table with the processed results. The date range picker and region dropdown filter the data by passing parameters to the Python endpoint. PyCharm's debugger can be attached to trace issues in the Python processing logic.
Common use cases
Build a machine learning inference endpoint for a Retool decision support panel
Develop a FastAPI service in PyCharm that loads a scikit-learn or PyTorch model, exposes a POST endpoint for predictions, and returns structured results with confidence scores. Connect the deployed endpoint to Retool as a REST API Resource so analysts can run model predictions from a Retool Form and view results in a Table with color-coded confidence indicators.
Build a Retool panel that sends customer data from a form to a FastAPI /predict endpoint, displays the returned prediction and probability scores in a Table, and highlights high-confidence predictions in green and uncertain predictions in yellow for analyst review.
Copy this prompt to try it in Retool
Create a Python data aggregation service for pandas-based reporting
Write a Flask service in PyCharm that reads from multiple data sources, runs pandas aggregations that would be complex in SQL alone, and returns clean summary data. Retool calls this service instead of running multiple database queries and JavaScript transformations, keeping complex logic in Python and reducing Retool app complexity.
Build a Retool dashboard that calls a Flask /report endpoint passing date range parameters, displays the returned sales performance aggregations in a Chart component, and shows cohort retention data in a Table — all computed by pandas on the Python backend.
Copy this prompt to try it in Retool
Expose internal Python ETL pipeline status to Retool operators
Develop a FastAPI service in PyCharm that reads pipeline job status from your task queue (Celery, RQ, or Airflow) and exposes status, progress, and error logs as REST endpoints. Wire these to a Retool monitoring panel where data engineers can view pipeline health, trigger reruns, and review error messages without needing direct terminal access.
Create a Retool pipeline monitoring panel that polls a FastAPI /pipelines endpoint every 30 seconds to display job status (running/completed/failed), shows progress bars for active jobs, and includes a Retry button that POSTs to /pipelines/{id}/retry to trigger a rerun from Retool.
Copy this prompt to try it in Retool
Troubleshooting
Retool query returns 'network error' or 'ECONNREFUSED' when connecting to a locally running Python service
Cause: Retool Cloud cannot reach localhost — it makes requests from Retool's servers, not your browser, so localhost addresses point to Retool's own servers, not your development machine.
Solution: For local development testing with Retool Cloud, use a tunneling tool like ngrok (ngrok http 8000) to expose your local Python service with a temporary public URL. Use this ngrok URL as your Resource base URL during development. Switch to the real deployment URL when the service is deployed to production. For self-hosted Retool on the same network as your service, internal hostnames work correctly.
Python service returns CORS errors when called from Retool
Cause: Retool Cloud proxies all Resource queries server-side, so CORS should not be an issue. If you're seeing CORS errors, the requests are being made by JavaScript in the browser rather than through a proper Retool Resource Query — this happens when using fetch() in a JavaScript query or custom component.
Solution: Use a REST API Resource Query instead of fetch() in JavaScript queries. Resource queries route through Retool's server-side proxy, which eliminates CORS entirely. If you need to call your Python service from a Retool custom component, use the Retool Resource Query API rather than direct fetch calls.
FastAPI or Flask endpoint returns 422 Unprocessable Entity when called from Retool
Cause: FastAPI's request validation is rejecting Retool's request because a required parameter is missing, has the wrong type, or is formatted differently than the Pydantic model expects.
Solution: In PyCharm's terminal, check the FastAPI logs for the validation error detail — FastAPI returns a detailed JSON error body explaining exactly which field failed validation and why. Match the Retool query's URL parameter types and names exactly to the FastAPI endpoint's parameter declarations. Use Optional[] types in FastAPI for parameters that may not always be sent by Retool.
1# Make all Retool-facing parameters Optional with defaults in FastAPI2from typing import Optional34@app.get("/api/orders")5async def get_orders(6 status: Optional[str] = Query(default=None),7 page: Optional[int] = Query(default=1),8 per_page: Optional[int] = Query(default=50)9):10 ...PyCharm HTTP client tests pass but the same endpoint returns different data in Retool
Cause: The PyCharm HTTP client test and the Retool query are sending different request parameters — different date formats, missing parameters, or different URL encoding of special characters.
Solution: Add the request logging middleware to your FastAPI service (see Step 5) and compare the logged request from PyCharm's HTTP client against the request from Retool. The log will show exactly what parameters each caller is sending, revealing any discrepancies in parameter names, values, or encoding.
Best practices
- Design Python API responses with Retool's component data binding in mind — flat arrays for Tables, time-series arrays for Charts, and single objects for detail panels — rather than having complex nested structures that require extensive JavaScript transformer work.
- Use PyCharm's HTTP client to test every endpoint before connecting to Retool, saving your .http files in the project repository so the whole team can reproduce API tests.
- Store API keys in environment variables loaded via python-dotenv in PyCharm development — never hardcode credentials in source code that gets committed to Git.
- Add comprehensive request logging middleware to your Python service to trace exactly what Retool sends versus what PyCharm tests send, making cross-system debugging straightforward.
- Use FastAPI over Flask for new Retool backend services — FastAPI's automatic OpenAPI docs (/docs), Pydantic validation, and async support make it significantly easier to maintain as an internal API.
- Always include pagination metadata (total, page, per_page, has_more) in list endpoint responses so Retool developers know how to implement pagination without guessing at the total record count.
- Deploy Python services with health check endpoints (/health) that Retool Workflows can poll to verify service availability before running critical operations.
- Use PyCharm's database tools (if on Professional) to inspect the database your Python service reads from — this makes debugging data discrepancies between your Python logic and the raw database values much faster.
Alternatives
IntelliJ IDEA supports Python through a plugin but is primarily optimized for JVM languages (Java, Kotlin, Scala) — PyCharm is purpose-built for Python with superior debugging and framework support.
VS Code with the Python extension is a free alternative to PyCharm for Python development, with similar terminal and HTTP client capabilities, while PyCharm Professional offers deeper framework integration and database tools.
Postman is a dedicated API testing tool that complements PyCharm for testing Python endpoints, while PyCharm's built-in HTTP client covers basic API testing without switching applications.
Frequently asked questions
Do I need PyCharm Professional or is Community Edition enough for Retool integration?
PyCharm Community Edition is sufficient for developing Flask and FastAPI services that Retool connects to. You can write code, run the debugger, and use the terminal to test endpoints. PyCharm Professional adds valuable extras: the built-in HTTP client for .http files, database tools for querying the databases your Python service reads from, and Docker integration for containerized deployments — all of which make the development workflow smoother but aren't strictly required.
Which Python framework works best for Retool backend services?
FastAPI is the recommended choice for new Retool backend services. Its automatic OpenAPI documentation (served at /docs) acts as living API documentation for your Retool developers. Pydantic validation catches parameter format issues before your endpoint code runs. Async support handles Retool's concurrent queries efficiently. Flask is a perfectly viable alternative if your team is more familiar with it — both frameworks serve JSON over HTTP and integrate identically with Retool REST API Resources.
How do I handle Retool's requests when my Python service needs database access?
Include your database connection logic directly in your Python service — use SQLAlchemy with a connection pool for PostgreSQL/MySQL, or the appropriate Python client library for your database. PyCharm's debugger makes it easy to trace data flow from the database query through pandas transformations to the JSON response. Keep database credentials in environment variables, and use the same database Retool would query directly — your Python service acts as a processing layer between the raw database and Retool's UI.
Can I use Jupyter notebooks developed in PyCharm to power Retool dashboards?
Not directly — Retool consumes REST API endpoints, not Jupyter notebooks. However, you can extract the Python logic from a Jupyter notebook, wrap it in a FastAPI endpoint function, and then connect that endpoint to Retool. PyCharm Professional has excellent Jupyter notebook support, making it easy to develop analytics logic in a notebook and then refactor it into a production FastAPI service for Retool consumption.
How do I secure my Python service so only Retool can call it?
The simplest approach is API key authentication with a shared secret stored in Retool's configuration variables. For additional security, whitelist Retool Cloud's IP ranges (35.90.103.132/30 and 44.208.168.68/30 for us-west-2) in your server's firewall or security group rules so only Retool's servers can reach your service. For self-hosted Retool, place both Retool and your Python service in the same VPC so network-level isolation handles access control without requiring application-level authentication.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation