# Quickstart: Build and deploy a Python (FastAPI) web app to Cloud Run

Learn how to use a single command to build and deploy
a "Hello World" web application from a code sample to Google Cloud
using Cloud Run.

By following the steps in this quickstart, Cloud Run automatically
builds a Dockerfile for you when you [deploy from source code](https://docs.cloud.google.com/run/docs/deploying-source-code).
For more information on how the Python buildpack determines the default
entrypoint for Cloud Run source deployments, see
[Build a Python application](https://docs.cloud.google.com/docs/buildpacks/python#entrypoint).

## Before you begin

1. To set the default project for your Cloud Run service, run the following command:

   ```bash
    gcloud config set project PROJECT_ID
   ```
   Replace <var translate="no">PROJECT_ID</var> with your Google Cloud project ID.
2. If you are under a domain restriction organization policy [restricting](https://docs.cloud.google.com/resource-manager/docs/organization-policy/restricting-domains) unauthenticated invocations for your project, you will need to access your deployed service as described under [Testing private services](https://docs.cloud.google.com/run/docs/triggering/https-request#testing-private).

3.


   Enable the Cloud Run Admin API and Cloud Build APIs, if any are not already enabled:


   **Roles required to enable APIs**


   To enable APIs, you need the `serviceusage.services.enable` permission. If you
   created the project, then you likely already have this permission through the
   Owner role (`roles/owner`). Otherwise, you can get this permission through the
   Service Usage Admin role (`roles/serviceusage.serviceUsageAdmin`).
   [Learn how to grant roles](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access).

   ```bash
   gcloud services enable run.googleapis.com cloudbuild.googleapis.com
   ```

   After the Cloud Run Admin API is enabled, the Compute Engine default service account is
   automatically created.
4. Review [Cloud Run
   pricing](https://cloud.google.com/run/pricing) or estimate costs with the [pricing calculator](https://cloud.google.com/products/calculator).

<br />

### Required roles


To get the permissions that
you need to complete this quickstart,

ask your administrator to grant you the
following IAM roles:

- [Cloud Run Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/run#run.admin) (`roles/run.admin`) on the project
- [Cloud Run Source Developer](https://docs.cloud.google.com/iam/docs/roles-permissions/run#run.sourceDeveloper) (`roles/run.sourceDeveloper`) on the project
- [Service Account User](https://docs.cloud.google.com/iam/docs/roles-permissions/iam#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on the service identity
- [Logs Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/logging#logging.viewer) (`roles/logging.viewer`) on the project


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access).


You might also be able to get
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

### Grant the Cloud Build service account access to your project

Cloud Build automatically uses the [Compute Engine default
service account](https://docs.cloud.google.com/build/docs/cloud-build-service-account) as the default
Cloud Build service account to build your source code and
Cloud Run resource, unless you override this behavior.

For Cloud Build to build your sources, grant the Cloud Build service
account the [Cloud Run
Builder](https://docs.cloud.google.com/iam/docs/roles-permissions/run#run.builder)
(`roles/run.builder`) role on your project:

```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
    --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \
    --role=roles/run.builder
```

Replace `PROJECT_ID` with your Google Cloud
project ID and `SERVICE_ACCOUNT_EMAIL_ADDRESS` with the
email address of the Cloud Build service account. If you're using the
Compute Engine default service account as the Cloud Build service account, then
use the following format for the service account email address:

```bash
PROJECT_NUMBER-compute@developer.gserviceaccount.com
```

Replace `PROJECT_NUMBER` with your Google Cloud
project number.

For detailed instructions on how to find your project ID, and project number,
see [Creating
and managing projects](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects).

Granting the Cloud Run builder role takes a couple of minutes to [propagate](https://docs.cloud.google.com/iam/docs/access-change-propagation).

## Write the sample application

To write an application in Python:

1. Create a new directory named `helloworld` and change directory
   into it:

       mkdir helloworld
       cd helloworld

2. Create a file named `main.py` and paste the following code into it:

   <br />

       from fastapi import FastAPI

       app = FastAPI()

       @app.get("/")

       def hello(name: str = "World"):
          """Return a friendly HTTP greeting."""
          return {
             "message": f"Hello {name}!"
          }

   This code creates a web service that responds to HTTP GET requests. HTTP
   handling is done by a FastAPI web framework in the container.
3. Create a file named `requirements.txt` and paste the following code into it:

       fastapi[standard]~=0.0

   This code adds packages needed by the sample.

Your app is finished and ready to be deployed.

## Deploy to Cloud Run from source

Deploy from source automatically builds a container image from source code
and deploys it.

To deploy from source:

1. In your source code directory, deploy the current folder using the
   following command:

   ```bash
   gcloud run deploy --source .
   ```
   1. When you are prompted for the service name, press Enter to accept the
      default name, for example `helloworld`.

   2. If you are prompted to enable additional APIs on the project,
      for example, the Artifact Registry API, respond by pressing
      `y`.

   3. When you are prompted for region: select the [region](https://docs.cloud.google.com/run/docs/quickstarts/build-and-deploy/deploy-python-fastapi-service#follow-cloud-run)
      of your choice, for example `europe-west1`.

   4. If you are prompted to create a repository in the specified region, respond by pressing `y`.

   5. If you are prompted to *allow public access* :
      respond `y`. You might not see this prompt if there is a domain
      restriction organization policy that prevents it; for more details see the
      [Before you begin](https://docs.cloud.google.com/run/docs/quickstarts/build-and-deploy/deploy-python-fastapi-service#before-you-begin) section.

   Then wait a few moments until the deployment is complete. On success, the
   command line displays the service URL.
2. Visit your deployed service by opening the service URL in a web browser.

> [!TIP]
> **Success:** You deployed a Python web app to Cloud Run.

### Cloud Run locations

<br />

Cloud Run is regional, which means the infrastructure that
runs your Cloud Run services is located in a specific region and is
managed by Google to be redundantly available across
[all the zones within that region](https://docs.cloud.google.com/docs/geography-and-regions).

<br />

Meeting your latency, availability, or durability requirements are primary
factors for selecting the region where your Cloud Run services are run.
You can generally select the region nearest to your users but you should consider
the location of the [other Google Cloud
products](https://cloud.google.com/about/locations/#locations) that are used by your Cloud Run service.
Using Google Cloud products together across multiple locations can affect
your service's latency as well as cost.  

Cloud Run is available in the following regions:

#### Subject to [Tier 1 pricing](https://cloud.google.com/run/pricing#tables)

- `asia-east1` (Taiwan)
- `asia-northeast1` (Tokyo)
- `asia-northeast2` (Osaka)
- `asia-south1` (Mumbai, India)
- `asia-southeast3 ` (Bangkok)
- `europe-north1` (Finland) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-north2` (Stockholm) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-southwest1` (Madrid) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west1` (Belgium) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west4` (Netherlands) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west8` (Milan) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west9` (Paris) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `me-west1` (Tel Aviv)
- `northamerica-south1` (Mexico)
- `us-central1` (Iowa) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `us-east1` (South Carolina)
- `us-east4` (Northern Virginia)
- `us-east5` (Columbus)
- `us-south1` (Dallas) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `us-west1` (Oregon) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)

#### Subject to [Tier 2 pricing](https://cloud.google.com/run/pricing#tables)

- `africa-south1` (Johannesburg)
- `asia-east2` (Hong Kong)
- `asia-northeast3` (Seoul, South Korea)
- `asia-southeast1` (Singapore)
- `asia-southeast2 ` (Jakarta)
- `asia-south2` (Delhi, India)
- `australia-southeast1` (Sydney)
- `australia-southeast2` (Melbourne)
- `europe-central2` (Warsaw, Poland) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west10` (Berlin)
- `europe-west12` (Turin) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west2` (London, UK) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `europe-west3` (Frankfurt, Germany)
- `europe-west6` (Zurich, Switzerland) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `me-central1` (Doha)
- `me-central2` (Dammam)
- `northamerica-northeast1` (Montreal) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `northamerica-northeast2` (Toronto) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `southamerica-east1` (Sao Paulo, Brazil) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `southamerica-west1` (Santiago, Chile) ![leaf icon](https://cloud.google.com/sustainability/region-carbon/gleaf.svg) [Low CO~2~](https://cloud.google.com/sustainability/region-carbon#region-picker)
- `us-west2` (Los Angeles)
- `us-west3` (Salt Lake City)
- `us-west4` (Las Vegas)

If you already created a Cloud Run service, you can view the
region in the Cloud Run dashboard in the
[Google Cloud console](https://console.cloud.google.com/run).
<button class="devsite-dialog-close">OK</button>

## Clean up

To avoid additional charges to your Google Cloud account, delete all the resources
you deployed with this quickstart.

### Delete your repository

Cloud Run doesn't charge you when your deployed service isn't in use.
However, you might still be [charged for storing the container image in
Artifact Registry](https://cloud.google.com/artifact-registry/pricing). To delete Artifact Registry repositories,
follow the steps in [Delete
repositories](https://docs.cloud.google.com/artifact-registry/docs/manage-repos#delete) in the Artifact Registry
documentation.

### Delete your service

Cloud Run services don't incur costs until they receive requests.
To delete your Cloud Run service, follow one of these steps:

### Console

To delete a service:

1. In the Google Cloud console, go to the Cloud Run **Services** page:

   [Go to Cloud Run](https://console.cloud.google.com/run/services)
2. Locate the service you want to delete in the services list, and click
   its checkbox to select it.

3. Click **Delete**. This deletes all revisions of the service.

### gcloud

To delete a service, run the following command:

```
gcloud run services delete SERVICE --region REGION
```

Replace the following:

- <var translate="no">SERVICE</var>: name of your service.
- <var translate="no">REGION</var>: Google Cloud region of the service.

### Delete your test project

Deleting your Google Cloud project stops billing for all resources in that
project. To release all Google Cloud resources in your project, follow these steps:

> [!CAUTION]
> **Caution** : Deleting a project has the following effects:
>
> - **Everything in the project is deleted.** If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
> - **Custom project IDs are lost.** When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an `appspot.com` URL, delete selected resources inside the project instead of deleting the whole project.

1. Delete a Google Cloud project:

```
gcloud projects delete PROJECT_ID
```

<br />

## What's next

For more information on building a container from code source and pushing to
a repository, see:

- [Developing Cloud Run services](https://docs.cloud.google.com/run/docs/developing)
- [Building Containers](https://docs.cloud.google.com/run/docs/building/containers)
- [Test a Cloud Run service locally](https://docs.cloud.google.com/run/docs/testing/local)
- [Deploying from source code](https://docs.cloud.google.com/run/docs/deploying-source-code)