# Add CORS to a Flask API

Yes. An agent adds CORS to your Flask app's API blueprint for the origins you name, with tests for the preflight and error paths, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/flask/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the repository into its own cloud sandbox and reads how the API is wired before it touches anything. In a Flask app like miguelgrinberg/microblog, `app/__init__.py` holds an application factory, `create_app`, that registers five blueprints; the JSON API is the `api` blueprint from `app/api/__init__.py`, mounted at `/api`, with the routes split across `app/api/users.py` and `app/api/tokens.py`. The other blueprints, `main` and `auth`, render HTML and use Flask-Login sessions. That split decides the shape of the change: CORS belongs on `/api/*` only, because a browser on another origin should be able to call the JSON routes with a token and should never be able to drive the session-based pages.

Then it reads the authentication and error handling the headers have to work with. `app/api/auth.py` builds two Flask-HTTPAuth objects: `basic_auth`, used by `POST /api/tokens` to trade a username and password for a token, and `token_auth`, a bearer scheme every other API route requires through `@token_auth.login_required`. Both error handlers return the JSON body from `error_response` in `app/api/errors.py`, which also maps any `HTTPException` on the blueprint to JSON. `create_user` in `users.py` answers 201 with a `Location` header pointing at `api.get_user`. `requirements.txt` pins `Flask==3.0.0` and `Flask-HTTPAuth==4.8.0` and has no CORS package, and `config.py` reads every setting from the environment through `python-dotenv`.

The change follows those conventions. The agent adds a pinned `Flask-Cors` line to `requirements.txt`, a `CORS_ORIGINS` setting in `config.py` read from an environment variable as a comma-separated list with an empty default, and in `create_app` applies CORS to the `api` blueprint only: the configured origins, the methods the routes use (GET, POST, PUT, DELETE, OPTIONS), `Authorization` and `Content-Type` as allowed request headers, `Location` as an exposed response header so a client can read where `create_user` put the new user, and credentials off, because the API uses bearer tokens rather than cookies. With no origins configured the app behaves exactly as before. Preflight `OPTIONS` requests are answered before `token_auth` runs, so a browser's preflight, which carries no `Authorization` header, is not refused with a 401.

The tests go into `tests.py`, the single unittest file the repository has, as a new test case class that uses the same `TestConfig` (an in-memory SQLite database and `ELASTICSEARCH_URL = None`) and the same `create_app` pattern as `UserModelCase`. They send an `OPTIONS` preflight to `/api/tokens` from an allowed origin and read the `Access-Control-Allow-Origin` and `Access-Control-Allow-Headers` answers, send a `GET /api/users/1` without a token and check that the 401 still carries the origin header so a browser can show the JSON error rather than a blocked request, send the same request from an origin not in the list and check no header comes back, and load `/auth/login` to check the HTML blueprint is untouched. The agent runs the whole file, commits with a note that `deployment/nginx/microblog` needs no change because the headers come from the application, and opens the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Do the work the Linear issue describes: add CORS to the JSON API of this Flask app, restricted to the origins the issue lists. Read requirements.txt, config.py, app/__init__.py, app/api/__init__.py, app/api/auth.py, app/api/errors.py, app/api/users.py, app/api/tokens.py, tests.py, boot.sh and deployment/nginx/microblog first. Add Flask-Cors to requirements.txt with a pinned version, a CORS_ORIGINS setting in config.py read from the environment as a comma-separated list with an empty default, and apply CORS in create_app to the api blueprint only: the configured origins, the methods the API routes use, Authorization and Content-Type as allowed headers, Location as an exposed header, credentials off. Preflight OPTIONS requests must succeed without a token. Do not touch the main or auth blueprints. Add a test case class to tests.py in the style of UserModelCase that covers a preflight from an allowed origin, a 401 that still carries the origin header, a request from an origin not in the list, and an HTML route with no CORS headers. Run the whole of tests.py and open a pull request that explains the CORS_ORIGINS variable for the deployment.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch with a small diff: one new line in `requirements.txt`, a setting in `config.py`, a few lines in `create_app`, and the new test class in `tests.py`. The description names the environment variable an operator sets, shows the exact header set a browser receives for an allowed origin, and states what was left alone: the `main` and `auth` blueprints, the nginx configuration under `deployment/`, and the `Dockerfile`, which installs from `requirements.txt` and so picks up the new package without a change of its own.

The run's transcript at `GET /o/{org}/sessions/{id}/messages` keeps the `pip install` and the unittest output, so a reviewer can see the test file ran in full, the four original user-model tests included, and read the raw preflight response the agent inspected with `curl` against the development server.

Before merging, a reviewer checks three things: that the origin list is configuration and not a wildcard, that `Access-Control-Allow-Credentials` is absent because the API authenticates with bearer tokens, and that the 401 test proves a browser client can read the JSON error body. A follow-up on the same session, such as asking to also allow a staging origin or to expose the `Link`-style pagination fields, continues in the same clone.

## Run it on every Linear issue labelled agent

Add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled` with `agent` among its labels. When someone on the team labels an issue that names the origins to allow, the trigger starts one run and puts the issue after the prompt, so the agent reads the origin list from the issue text; the prompt holds no placeholder to fill. A label applied by an app integration never fires the trigger, and `max_runs_per_hour` caps how many labelled issues the automation takes on in an hour.

From your own server, a handler that receives Linear's webhook sends `POST /o/{org}/sessions` with the repository and the issue URL, `https://linear.app/<workspace>/issue/<ID>`, in `resources`, which puts the issue in the prompt through your Linear connection, and a `request_id` that is a UUID v5 of the issue id so a redelivered webhook returns the run already started. Give that key a `webhook_url` and Rush POSTs `run.completed` with `data.session_url` when the pull request is open.

## Why run it on Rush?

CORS mistakes are quiet: a wildcard origin with credentials, or a missing `Access-Control-Allow-Origin` on the 401 path, ships without a failing test and surfaces as a blank browser console on someone else's machine. The agent works in its own sandbox with the app's real dependency set, writes the preflight and error-path tests next to the existing ones, and runs them before the pull request exists, so the behaviour is proven on the branch rather than described in a comment.

Every command and its output stay with the run. The `curl` of the preflight, the test output and the diff are all in the transcript, and the pull request links to them. A team with several Flask services starts one run per repository with the same request and gets one pull request each, with the origin list taken from each issue.

## Frequently asked questions

### Does it open the API to every origin?

No. The allowed origins come from a `CORS_ORIGINS` environment variable the agent adds to `config.py`, and with nothing set the app answers exactly as it does today. A wildcard would be a deliberate choice in the deployment's environment, not something the pull request puts in code.

### Why only the api blueprint?

The `main` and `auth` blueprints render HTML and rely on Flask-Login session cookies, where cross-origin requests are the thing to prevent. The JSON routes under `/api` use bearer tokens from `app/api/auth.py`, which is the authentication model CORS is safe with, so the headers go there and nowhere else.

### Will the preflight fail because every API route needs a token?

No. A browser's `OPTIONS` preflight carries no `Authorization` header, so if it reached `@token_auth.login_required` it would get a 401 and the real request would never be sent. Flask-Cors answers the preflight before the view runs, and the new test sends one to `/api/tokens` to prove it.

### Does the nginx or gunicorn setup need to change?

No. `boot.sh` runs gunicorn, `deployment/nginx/microblog` proxies to it and serves `/static` directly, and neither adds or strips these headers. The headers come from the application, so the only deployment change is setting the new variable.

### What if the Linear issue does not say which origins?

The agent asks on the issue instead of guessing, as the automation prompt in the Linear label to PR use case does. An origin list is a security setting, so it is read from the issue text, never invented.

## More Flask jobs

- [Add a Feature to a Flask App from a Customer Spec](https://getrush.ai/run/add-feature-per-customer/flask/)
- [Set Up GitHub Actions CI for a Flask App](https://getrush.ai/run/add-github-actions-ci/flask/)
- [Add Health Checks to a Flask App](https://getrush.ai/run/add-health-checks/flask/)

## The same job on other stacks

- [Add CORS to a Gin API](https://getrush.ai/run/add-cors/gin/)
- [Add CORS to a Hono API](https://getrush.ai/run/add-cors/hono/)
- [Add CORS to a Koa App](https://getrush.ai/run/add-cors/koa/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
