Skip to main content

Deploying FastAPI on Azure Using VS Code Extensions

· 9 min read
Shivam Pawar
Senior Software Developer @Bridgenext

Sometimes we want to deploy an API on Azure quickly for POC (Proof of Concept) purposes, testing ideas, or sharing prototypes without setting up complex infrastructure. FastAPI, being a modern, fast web framework for building APIs with Python, is perfect for such scenarios due to its high performance, automatic API documentation, and ease of use. In this comprehensive blog post, we'll walk through deploying a simple FastAPI application to Azure App Service using the Azure extensions available in Visual Studio Code. This approach is straightforward, leverages the power of VS Code's integrated tools to streamline the process, and allows developers to focus on coding rather than infrastructure setup. By the end of this guide, you'll have a fully functional API running on Azure, accessible from anywhere.


Prerequisites

Before we dive into the deployment process, let's ensure you have all the necessary tools and accounts set up. This will make the entire process smooth and error-free.

  • A basic FastAPI application: If you already have a FastAPI app ready, great! If not, we'll create a simple one in the next step. FastAPI is chosen for its speed and simplicity in building APIs.
  • Python installed on your machine (version 3.7 or higher): Python is the core language for FastAPI. Ensure it's installed and accessible from your command line.
  • Visual Studio Code (VS Code) installed: VS Code is a powerful, free code editor with excellent support for Python and Azure integrations.
  • An Azure account: You'll need an active Azure subscription to deploy to Azure App Service. If you don't have one, sign up for a free account at azure.com, which includes credits for experimentation.
  • VS Code extensions: Install the Azure App Service and Azure Account extensions from the Extensions view in VS Code (accessible via Ctrl+Shift+X). These extensions provide seamless integration with Azure services directly from your editor.

Step 1: Create a Simple FastAPI Application

If you already have a FastAPI application ready for deployment, you can skip this step. However, for the purpose of this tutorial, we'll build a minimal FastAPI app from scratch to demonstrate the deployment process. This will give you a complete understanding of how everything fits together.

Start by creating a new directory for your project. This keeps your code organized and isolated.

mkdir fastapi-azure-demo
cd fastapi-azure-demo

Next, set up a virtual environment. Virtual environments are crucial in Python development as they allow you to manage dependencies for different projects separately, preventing conflicts between packages.

python -m venv venv
# On Windows
venv\Scripts\activate
# On Linux/Mac
source venv/bin/activate

With the virtual environment activated, install FastAPI and Uvicorn. FastAPI is the web framework we'll use to build our API, while Uvicorn is an ASGI server that will run our application.

pip install fastapi uvicorn

Now, create the main application file. This file defines our API endpoints.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

Create a requirements.txt file to list all dependencies. This file tells Azure what packages to install during deployment.

fastapi
uvicorn[standard]

Finally, test your application locally to ensure everything works before deploying.

uvicorn main:app --reload

Open your browser and visit http://127.0.0.1:8000 to see your API in action. You should see a JSON response with "Hello": "World". You can also test http://127.0.0.1:8000/items/1 to see the parameterized endpoint.

Step 2: Install Azure Extensions in VS Code

To integrate Azure services directly into your development environment, we need to install specific extensions in VS Code. These extensions provide a graphical interface for managing Azure resources without leaving your code editor.

Open VS Code and navigate to the Extensions view by pressing Ctrl+Shift+X or clicking the Extensions icon on the sidebar. In the search bar, look for and install the following extensions:

  • Azure App Service: This extension allows you to deploy web apps, manage app settings, and monitor your applications directly from VS Code.
  • Azure Account: This extension handles authentication with your Azure account, enabling secure access to your Azure resources.

Once installed, sign in to your Azure account. Click on the Azure icon that appears in the VS Code sidebar after installing the extensions. Follow the prompts to authenticate. This step is essential as it grants VS Code permission to interact with your Azure subscription.

With these extensions installed and your account connected, you're now ready to deploy your application to Azure seamlessly.

Step 3: Prepare Your Application for Deployment

Before deploying to Azure, we need to ensure our application is properly configured for the cloud environment. Azure App Service will automatically install dependencies and run our app, but we need to provide the necessary configuration files.

First, double-check your requirements.txt file. This file tells Azure which Python packages to install. For our simple FastAPI app, it should include:

fastapi
uvicorn[standard]

If your application has additional dependencies, make sure they're all listed here. You can generate this file automatically by running pip freeze > requirements.txt in your activated virtual environment.

Next, create a startup.txt file. This file specifies the command Azure should use to start your application. For FastAPI with Uvicorn, the command is:

uvicorn main:app --host 0.0.0.0 --port 8000

The --host 0.0.0.0 ensures the app listens on all network interfaces, which is necessary in a containerized environment like Azure App Service. The --port 8000 specifies the port, though Azure may override this.

With these files in place, your application is ready for deployment. Azure will use requirements.txt to install dependencies and startup.txt to launch your app.

Step 4: Deploy to Azure App Service

Now comes the exciting part – deploying your FastAPI application to Azure! The Azure App Service extension in VS Code makes this process incredibly straightforward. Follow these steps carefully:

  1. Open your project folder in VS Code: Make sure the folder containing your main.py, requirements.txt, and startup.txt is open in VS Code.

  2. Initiate deployment: Right-click on the folder in the Explorer panel and select "Deploy to Web App..." Alternatively, open the Command Palette (Ctrl+Shift+P) and search for "Azure App Service: Deploy to Web App".

  3. Sign in if prompted: If you haven't signed in yet, the extension will prompt you to authenticate with Azure.

  4. Select your subscription: Choose the Azure subscription you want to use for this deployment.

  5. Choose or create a Web App: You can select an existing App Service or create a new one. For this tutorial, we'll create a new one. Provide a unique name for your app (this will be part of your URL), select Python as the runtime stack, and choose a version (e.g., Python 3.9).

  6. Select a resource group: Resource groups help organize your Azure resources. Create a new one or select an existing one.

  7. Choose a hosting plan: For POC purposes, select the Free tier. This gives you a basic App Service plan at no cost, though with limitations on resources.

  8. Deployment process: VS Code will now package your application into a ZIP file, upload it to Azure, and trigger the deployment. This process involves zipping your project files, pushing the ZIP to Azure Blob Storage, and then Azure App Service unzipping and deploying it. Be patient, as this can take several minutes depending on your internet connection and Azure's current load.

  9. Deployment completion: Once finished, VS Code will display the URL of your deployed application. Note this down for testing.

Step 5: Verify the Deployment

With your application deployed, it's time to verify that everything is working correctly in the cloud. This step ensures your API is accessible and functioning as expected.

Navigate to the URL provided by VS Code after deployment (something like https://your-app-name.azurewebsites.net).

You should see your FastAPI application running. Test the root endpoint by visiting the URL directly – it should return a JSON response like {"Hello": "World"}.

To thoroughly test your API, try the parameterized endpoint: https://your-app-name.azurewebsites.net/items/1?q=test. This should return something like {"item_id": 1, "q": "test"}.

Additionally, FastAPI automatically generates interactive API documentation. Visit https://your-app-name.azurewebsites.net/docs to access the Swagger UI, where you can explore and test all your API endpoints directly in the browser.

Alternatively, https://your-app-name.azurewebsites.net/redoc provides another documentation interface.

If your application isn't starting properly, it might be due to startup command configuration. In such cases, head to the Azure portal, locate your App Service, and navigate to Configuration > General settings. Here, you can set the startup command. An example command for our FastAPI app is: uvicorn main:app --host 0.0.0.0 --port 8000.

Once verified, your FastAPI API is live on Azure and ready for use!

Troubleshooting

Even with careful preparation, issues can arise during deployment or runtime. Here are some common problems and their solutions:

  • Deployment fails: First, check the output in VS Code's terminal for error messages. These often provide clues about what's going wrong, such as missing files or incorrect configurations.

  • Inaccurate requirements.txt: Ensure all your dependencies are correctly listed in requirements.txt. Missing packages can cause import errors during startup.

  • Application running but behaving unexpectedly: If your app starts but doesn't respond as expected, check the logs. You can access these via the Azure portal under Monitoring > Log stream, or use the Azure App Service extension in VS Code to view logs in real-time.

  • Deployment issues: Review the Deployment Center in the Azure portal for a history of deployments, their status, and any error messages. This can help identify problems with the deployment process itself.

  • Production considerations: For production deployments, always use environment variables for sensitive data like API keys or database connections. Also, enable application logging to monitor your app's behavior over time.

This method of deploying FastAPI applications to Azure using VS Code extensions is ideal for quick deployments and POCs. It eliminates the need for complex infrastructure setup, allowing developers to focus on building and testing their APIs. The integration between VS Code and Azure makes the entire process seamless and efficient.

For more advanced setups, consider exploring other Azure services like Azure Functions for serverless APIs or Azure Container Instances for containerized deployments. As your application grows, you might also want to look into scaling options, custom domains, and integration with other Azure services like Azure Database for persistent storage.

Happy coding! With this knowledge, you're now equipped to rapidly deploy Python APIs to the cloud.

If you found this article useful, please share it with your friends and colleagues!❤️

Read more articles on ➡️ Dev.To

Follow me on ⤵️