> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://help.squarecloud.app/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# How to host a FastAPI application

## 1. Prerequisites

* **Square Cloud Account:** Create your account via the [Registration Page](https://squarecloud.app/en/signup) (Email or GitHub).
* **Active Plan:** A paid plan is required for hosting. Check the [pricing here](https://squarecloud.app/en/pricing).

---

## 2. Network Configuration

For your API to be externally accessible, the web server must be configured to operate on port **80**. Unlike local environments (where we use 8000), Square Cloud uses port 80 for public routing.

### Code Structure Example (`app/main.py`)
```python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"status": "online", "framework": "FastAPI"}
```

---

## 3. Performing the Deployment

1.  **Project Cleanup:** Remove cache folders like `__pycache__` or virtual environment folders (`.venv`).
2.  **Compression:** Create a `.zip` file containing your code folder (e.g., `app/`) and the `requirements.txt` file.
3.  **Upload:** In the Square Cloud Dashboard, upload the `.zip` file.
4.  **Web Publishing:** During submission, locate and check the **"Publish to Web"** option.
5.  **Subdomain:** Define the name of your free subdomain (e.g., `my-api.squareweb.app`).
6. **Production Start Command:** FastAPI now features a built-in CLI command that simplifies production execution, ensuring that the server utilizes workers efficiently and listens on the correct port.
At the time of upload or in your `squarecloud.app` file, set the start command to:
```bash
python -m fastapi run app/main.py --port 80
```
* **`run`**: Command optimized for production execution.
* **`app/main.py`**: The path to the file where your FastAPI instance is located.
* **`--port 80`**: Defines the mandatory port for functioning on Square Cloud.

---

## 5. Custom Domains (Standard+ Plan)

If you use the **Standard plan or higher**, you can configure a professional domain (e.g., `api.yourdomain.com`):
* The configuration is done in the **Network** tab of the Dashboard.
* **SSL (HTTPS)** is automatically generated, ensuring your API is secure by default.

---

## 6. Performance Tips

* **Automatic Validation:** FastAPI uses Pydantic for data validation. Make sure to define schemas to gain performance in JSON serialization.
* **Environment Variables:** Use the **ENV** tab in the Dashboard to manage security keys and database connections, accessing them via `os.getenv()`.
* **Monitoring:** Follow real-time logs via the Dashboard to check the loading of the server workers.
```