Deploying FastAPI Applications on Google App Engine: A Guide
Written on
Introduction
Google App Engine
Google App Engine (GAE) is a fully managed PaaS solution offered by Google Cloud. It allows developers to create and deploy scalable web applications without the hassle of managing the underlying infrastructure. GAE simplifies the deployment, scaling, and maintenance processes, enabling developers to focus on coding their applications.
With App Engine, developers can utilize popular programming languages such as Python, Java, Node.js, and Go to build applications that automatically adjust to incoming traffic. The platform abstracts server management complexities, allowing developers to prioritize feature creation over server provisioning and scaling issues.
Key features that make GAE appealing include:
- Automatic Scaling: GAE automatically adjusts resources according to traffic, ensuring optimal performance and cost-effectiveness.
- Multi-Language Support: Developers can select from various languages, including Python, Java, and Node.js, providing flexibility for diverse project needs.
- Managed Infrastructure: Google oversees server provisioning, monitoring, and maintenance, allowing developers to concentrate on coding and innovation.
- Built-in Datastore: A NoSQL database for scalable data storage and retrieval.
- Task Queue Services: Facilitates background processing, enhancing application responsiveness.
- Authentication Services: Simplifies user authentication and authorization processes.
- Deployment Options: Supports easy deployment through command-line tools or IDEs, streamlining the development-to-production workflow.
- Versioning and Traffic Splitting: Enables deployment of multiple application versions with the ability to split incoming traffic, facilitating gradual rollouts and A/B testing.
- IDE Support: Integrates seamlessly with popular IDEs like Eclipse and IntelliJ, simplifying development.
- Monitoring and Logging: Offers tools for performance monitoring, error tracking, and log analysis to ensure efficient operation.
- Custom Runtimes: Allows for the use of custom runtimes for applications written in unsupported languages.
- Security Features: Includes automatic data encryption, traffic segregation, and IAM controls.
FastAPI
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ that utilizes standard Python type hints. It aims to be user-friendly while producing efficient code. Built on Starlette and Pydantic, FastAPI harnesses their capabilities for an effective web framework.
Key features of FastAPI include:
- Speed: FastAPI is optimized for high performance, employing asynchronous programming to handle multiple requests efficiently.
- Type Hints: It utilizes Python type hints for automatic data validation, serialization, and documentation generation, helping catch errors early and automatically creating OpenAPI and JSON Schema documentation.
- Asynchronous Support: Natively supports asynchronous programming, allowing for enhanced performance in scenarios requiring concurrent request handling.
- Automatic Documentation: Generates interactive API documentation from provided type hints, accessible via a web browser, detailing request and response models, endpoints, and more.
- Dependency Injection: Utilizes a dependency injection system to manage application dependencies, simplifying code organization and testing.
- Data Validation: Employs Pydantic models for data validation, ensuring incoming data adheres to expected structures and types.
- WebSocket Support: Facilitates real-time applications through WebSocket communication, allowing bidirectional client-server interaction.
- Security Features: Incorporates built-in security measures, such as automatic request payload validation and OAuth2 support.
Deploying a FastAPI Application on Google App Engine
Step 1: Create a FastAPI Application
Begin by creating a minimal FastAPI application. In a main.py file, declare a single root endpoint (/) that returns a JSON response:
from fastapi import FastAPI from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/") def index():
return JSONResponse(
content={
"message": "Hello from Google App Engine!"}
)
Next, start the application in a terminal using the gunicorn server:
gunicorn -w 1 -k uvicorn.workers.UvicornWorker main:app
Then access it in your browser at localhost:
Step 2: Create Dependencies for Python Runtime
Create a requirements.txt file for your project's dependencies. For this minimal app, it only requires FastAPI:
fastapi==0.104.1 uvicorn==0.24.0.post1 gunicorn==20.1.0
These dependencies will be installed and utilized when your code is deployed on Google App Engine.
Step 3: Create Google App Engine YAML Configuration File
A simple YAML configuration will suffice for this demo:
service: default entrypoint: gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app runtime: python311 instance_class: F1
automatic_scaling:
min_instances: 0
max_instances: 10
- service: Name and reference for the GAE service in Google Cloud Console.
- entrypoint: Command to launch the app engine instances using the gunicorn server.
- runtime: The runtime for the application, in this case, Python 3.11.
- instance_class: Reference name for resource specification.
- automatic_scaling: Configuration for automatic scaling, with minimum instances set to 0 and maximum to 10.
Refer to the documentation for more YAML options and custom configurations, including limits, security, and efficiency features.
Step 4: Create a Google Cloud Project
To utilize Google Cloud Platform, you need a Google account, which comes with $300 in free credits valid for 90 days. Google Cloud also offers numerous products under a free tier based on usage. Visit https://cloud.google.com and click on the console link in the top right corner to access the browser-based console.
Locate the project selection in the top left corner, click the dropdown, and choose the option to create a new project. Assign a name to your project (this will be the project ID). I named mine fastapi-deploy-example. Your project will be initialized with default APIs enabled.
Step 5: Set Up a Billing Account for Your Project
Even if your project will only operate within the free tier, you must set up a billing account. Use the search bar to locate the billing module and create an account for your project. Provide your details and a debit/credit card for verification. Google will perform a $0 amount transfer to authenticate your bank account.
Link your billing account to the App Engine module by searching for the module, entering it, and connecting it to the newly created billing account.
Step 6: Install Google Cloud CLI
To deploy code on Google Cloud Platform, you'll need the Google Cloud Command Line Interface (CLI), known as gcloud. Download and install the latest version from the official documentation according to your host platform.
After installation, initialize the CLI using gcloud init. During this setup, you'll select or set up an account for the CLI, including authentication and configuration.
Step 7: Deploy FastAPI App on Google App Engine
Before deploying, ensure your account and project are correctly set up via the gcloud CLI. Here’s how your configuration might look in the CLI:
gcloud config list
To refresh permissions, you may need to run:
gcloud auth application-default login
Now, deploy your app:
gcloud app deploy --project=fastapi-deploy-example --version=v1
The output will provide details about the deployment, including the YAML configuration, source code location, and the target URL for your service. Confirm the deployment by typing y and hitting enter.
After deployment, you can stream logs from the command line using:
gcloud app logs tail -s default
To view your application in a web browser, run:
gcloud app browse
You should see the same output as in your local environment! Additionally, you can access the automatically generated documentation for your FastAPI at the default URL paths for docs and redoc.
Conclusion
In summary, deploying your FastAPI application on Google App Engine simplifies web development by removing infrastructure concerns. The automatic scaling and managed infrastructure of GAE make deployment easier, while FastAPI's performance, asynchronous support, and built-in security features enhance the development experience. Follow this guide for a seamless deployment process and leverage the strengths of both technologies for building and scaling serverless web applications. Happy coding!
That’s all folks!
I hope you find this guide useful. Please share your feedback in the comments section and feel free to follow for more content like this.