Deploy FastAPI on Railway for an AI app backend
Short answer: run FastAPI on Railway as a Python web service with an ASGI server, the correct module path and a listener on 0.0.0.0 using the configured PORT. Add backend secrets in Railway Variables and a health endpoint before connecting your frontend. PostgreSQL is optional until the API needs persistent records.
What this deployment is for
A separate Python API is useful when a generated frontend needs server-side Python libraries, controlled calls to an AI provider or database access behind application logic. Keep the boundary explicit: the frontend makes HTTPS requests to the API, and the API handles privileged operations.
This guide shows a small connectivity example. It is not an authenticated product backend. Add authentication, authorization and request limits before exposing a paid provider or private records through new endpoints.
Prepare a minimal API
For an example project with main.py at the repository root, define a health route:
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}
Declare fastapi and uvicorn[standard] in your project’s dependency manifest, then lock the versions you test. Use your existing dependency manager rather than introducing a second one for deployment. Run the app locally and confirm the endpoint before pushing it.
The production command for this layout can be:
uvicorn main:app --host 0.0.0.0 --port $PORT
Here main means main.py and app is the Python object. A file at backend/main.py may need a different working directory or module path. The $PORT expression must be expanded by the startup environment; a custom Docker exec-form command does not perform shell substitution automatically.
FastAPI’s manual server documentation explains ASGI server startup. Do not use the development auto-reload process as your production command.
Deploy from your repository
- Commit the code and dependency files. Keep real secrets and local virtual environments out of Git.
- Create a Railway project from the GitHub repository. Set the correct root directory if the API is inside a larger app.
- Check the dependency installation and start command. Confirm that Uvicorn is available in the deployed environment and that the import path matches your files.
- Add backend variables. Set any external API credentials on the API service, not the frontend service.
- Configure
/healthas the health-check path. Deploy and inspect the runtime logs for startup errors. - Generate a public domain. Request
/healthon that domain and confirm a successful response before testing more routes.
Railway’s FastAPI deployment guide covers repository, CLI, template and Docker routes. Your existing repository may use a different ASGI server; keep a working, documented configuration rather than switching solely to match this example.
Connect a separately hosted frontend
The frontend needs the public HTTPS API URL. It cannot use a Railway private hostname from the visitor’s browser. If the two origins differ, configure CORS for the exact frontend origins you intend to permit.
For example, add this to the example above after creating app, replacing the placeholder with your real frontend origin:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_methods=["GET"],
allow_headers=[],
)
This allows the example’s read request; extend methods and headers deliberately for your real endpoints. Cookie authentication or authorization headers need their own configuration. FastAPI’s CORS guide explains origins, credentials and explicit allowlists. A permitted origin does not authenticate a user.
Test through the actual frontend as well as a direct API request. Browser security rules can reveal a configuration problem that a command-line request does not exercise. Check the destination URL after every frontend configuration change.
Add Postgres when records need to persist
If the API stores accounts or application records, deploy a compatible database in the same Railway project environment and reference its private connection variable. Keep schema changes in migrations and plan a restore before collecting valuable data.
If it also accepts uploaded files, give those bytes their own persistent destination. See Railway volumes versus buckets for mount paths, private object access and a redeploy test; a row containing a filename does not preserve the file itself.
The Postgres with pgvector template includes pooling and daily backups and can serve ordinary SQL applications. Its direct and pooled connections have different uses; read the template’s connection notes before choosing one for migrations.
Deploy Postgres for FastAPIVerify behavior and cost
Test a permitted request, an invalid input and an unauthorized operation once your real endpoints exist. Make sure logs help diagnose failures without printing tokens or complete credentials. A passing health route proves connectivity, not the correctness of every business operation.
The API, database and any background workers contribute to hosting usage; model calls have their own provider bill. Review Railway pricing and environment variables. If the API never answers publicly, use the 502 troubleshooting checklist before changing the application’s data model.
FAQ
What start command should FastAPI use on Railway?
For an app object named app in main.py, one option is uvicorn main:app --host 0.0.0.0 --port $PORT. Install Uvicorn, match the module path to your repository and make sure the startup environment expands PORT.
Why does my FastAPI API work in a browser tab but fail from my frontend?
Inspect the browser console and network response. Cross-origin requests may need CORS configuration allowing the frontend's exact origin. CORS does not replace API authentication or authorization.
Do I need Postgres for a FastAPI deployment?
No. A small API can run without a database. Add persistent storage when the application needs records, and use migrations and a tested backup process for valuable data.
Should the frontend contain my model API key?
No. Keep the provider key in the FastAPI service's backend variables. Authenticate calls to your API and apply usage controls before forwarding requests to a paid model provider.