- Notifications
You must be signed in to change notification settings - Fork3
Web API using FastAPI framework
License
oleksis/napptive-playground-py
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Run a Python API in this ready-to-use-repository in minutes
By opening this template respository in Codespaces, you can quickly get hands-on with a Python web app that serves an HTTP API using theFastAPI framework. You'll get to focus on working with the project instead of setup and configuration.
🤔 Curious? Watch the following video where we explain all the details:
Learn more about APIs
An API (Application Programming Interface) describes a way for two computers to interact.An HTTP API allows an Internet-connected computer to send an HTTP request to another Internet-connected computerand receive a response. For example, my computer could send a request tohttp://a-weather-website-api.com/api/city=Los+Angeles
and receive back data like{"high": 72, "low": 66}
.
HTTP APIs often provide either data or functionality that's unique to a service, like the example API for the weather website. A weather website could provide additional API endpoints for other weather-related functionality, like upcoming forecasts or historical data. Any website can decide to offer an API if it thinks it has helpful functionality to sharewith other computers. In this project, you'll run an HTTP API that generates a random token.
This template is also ready to be used withCodespaces, a developer environment running in the cloud withVisual Studio Code.
Using Codespaces, you getVisual Studio Code in the cloud, using a"development container". Like a locally running version ofVisual Studio Code, the cloud version also allows you to install extensions and use a terminal.
You can also configure your development container to run a specific runtime and have it boot up with your favorite extensions.
Here are the key files and folders that make it happen:
- webapp/: The HTTP API code, built with the FastAPI framework.
- .devcontainer/Dockerfile: Configuration file used by Codespaces to determine operating system and other details.
- .devcontainer/devcontainer.json, A configuration file used by Codespaces to configureVisual Studio Code settings, such as the enabling of additional extensions.
Try out this template repository using Codespaces following these steps:
Create a repository from this template. Use thiscreate repo link. You can make the repository private or public, up to you.
Navigate to the main page of the newly created repository.
Under the repository name, use the Code drop-down menu, and in the Codespaces tab, select "Create Codespace on main".
What you have at this point is a pre-configured environment where all the runtimes and libraries you need are already installed - a zero config experience.
This Python application is using FastAPI, a powerful web framework that self-documents its API endpoints. The API has only one endpoint that generates a unique pseudo-random string that can be used as a token.
Run FastAPI inside the Codespace
The API included in this template repository has a single endpoint that generates a token. Get it up and running using the following steps:
Open up a terminal window by opening up the command palette (Ctrl-Shift-P or Cmd-Shift-P) and then select "Open new Terminal" command.
Run
uvicorn
in the console to start up your API application:uvicorn --host 0.0.0.0 webapp.main:app --reload
You should see output similar to:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO: Started reloader process [28720]INFO: Started server process [28722]INFO: Waiting for application startup.INFO: Application startup complete.
You'll get a pop-up that says your application is available at port 8000. Click the button to open it in the browser.
Once the site loads, click on theTry it Out button or append
/docs
to the URL in the address bar. The automatically generated API documentation should load and look like this:Finally, try to interact with the API by sending a request using the self-documented page. Click on thePOST button and then on theTry it Out button:
🔒 Do you see the lock next to the URL of the website in the browser? That indicates the website is being served over a secure HTTPS connection which encrypts the HTTP responses. That's very important whenever an API can receive sensitive data or respond with sensitive data (like a password).
You can change your environment and the text editor so that the next time you create (or rebuild) the environment, everything will be set automatically. Let's go through two different challenges that you are likely to want to do:
- Changing the Python version
- Adding or modifying a pre-installed editor extension
Let's say you want to change which version of Python is installed. This is something you can control.
Open.devcontainer/devcontainer.json and replace the following section:
"VARIANT":"3.8-bullseye"
with the following instruction:
"VARIANT":"3.9-bullseye"
This change instructs Codespaces to use Python 3.9 instead of 3.8.
If you make any configuration change indevcontainer.json
, a box will appear after saving.
Click on rebuild. Wait for your Codespace to rebuild the VS Code environment.
Your environment comes with pre-installed extensions. You can change which extensions your Codespaces environment starts with. Here's how:
Open file.devcontainer/devcontainer.json and locate the following JSON elementextensions:
"extensions": ["ms-python.python","ms-python.vscode-pylance"]
Add"ms-python.black-formatter" to the list of extensions. It should end up looking like the following:
"extensions": ["ms-python.python","ms-python.vscode-pylance","ms-python.black-formatter"]
That string is the unique identifier ofBlack Formatter, a popular extension for formatting Python code according to best practices. Adding the"ms-python.black-formatter" identifier to the list lets Codespaces know that this extension should be pre-installed upon startup.
Reminder: When you change any configuration in the JSON file, a box will appear after saving.
Click on rebuild. Wait for your Codespace to rebuild the VS Code environment.
To find the unique identifier of an extension:
- Navigate to the extension's web page, for examplehttps://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter
- Locate theUnique Identifier field underMore info section on your right side.
Take this API application to the next level and deploy it to the cloud! For this learning challenge you'll use a FREE deployment option for Azure and GitHub Actions for the automation.
Before continuing, make sure you have an Azure account ready. Select any of the following:
- Sign in to your Azure account
- Create a (no Credit Card required) Azure For Students account
- Create a new Azure account
There are a few steps involved, so make sure you get everything right!
Create an Azure App Service
Now, you are going to set up automatic deployment of the application using Azure plus GitHub actions! However, you first need to configure some Azure services.
- Open theAzure Cloud Shell.
- Use the Bash shell (not PowerShell!) for these steps.
- If it says "You have no storage mounted", select a subscription in your account and click "Create storage". The Cloud Shell uses that storage resource to store data generated during your shell sessions.
- Create aResource Group which will group together the different Azure resources used for the app:
az group create --name demo-fastapi --location "East US"
- You'll see a JSON response with details about the newly created resource, for this command and all the commands that follow.
- Create theFREEApp Service Plan:
az appservice plan create --name "demo-fastapi" --resource-group demo-fastapi --is-linux --sku FREE
- Create a random identifier for a unique webapp name:
let "randomIdentifier=$RANDOM*$RANDOM"
- Create theWeb App Service with a placeholder container using the
randomIdentifier
variable from before:
az webapp create --name "demo-fastapi-$randomIdentifier" --resource-group demo-fastapi --plan demo-fastapi --runtime "PYTHON:3.9"
- Head to the Azure portalApp Services list and confirm that your newly created service is listed.
Create an Azure Service Principal
Next, create an Azure Service Principal, which is a special type of account that has permissions necessary to authenticate from GitHub to Azure:
- Find the ID of your Azure Subscriptionin the Azure portal orby following this guide.
- Create a Service Principal with a "contributor" role that is allowed to make changes to any resources in that subscription. Replace $AZURE_SUBSCRIPTION_ID with the ID you found in step 1 and run this command:
az ad sp create-for-rbac --sdk-auth --name "github-deployer" --role contributor --scopes /subscriptions/$AZURE_SUBSCRIPTION_ID
- Capture the output and add it as aGithub repository secret with the name
AZURE_CREDENTIALS
. (If that link doesn't work, make sure you're reading this on your own copy of the repo, not the original template.)
Setup GitHub Actions
Now that you have all the Azure resources created, you need to update the GitHub Action workflow file with the name of your webapp.
- Find your app name. It should look something like
demo-fastapi-97709018
but with a different random number at the end,and you can find it in the Azure portal or the Cloud Shell commands. - Open the.github/workflows/web_app.yml file and update the value of
AZURE_WEBAPP_NAME
to your app name. - Commit and push the changes to the Github repository:
git add .github/workflows/web_app.ymlgit commit -m "Updating workflow file"git push
🏃 Deploy your app!
Before continuing, check the following:
- You've created an Azure Service Principal and saved it as arepository secret as
AZURE_CREDENTIALS
. - You've created anApp Service with a valid name and the site is already available with the default static content.
To deploy:
- Navigate torepository actions. (If that link doesn't open the "Build and deploy Python app" workflow, make sure you're reading this on your own copy of the repo.)
- SelectRun workflow and select the green button inside the pop-up to run the workflow.
Deploying can take a couple of minutes. Make sure you stream the logs in the Azure Cloud Shell to check the progress:
az webapp log tail --name $AZURE_WEBAPP_NAME --resource-group $AZURE_RESOURCE_GROUP
- Once deployment is complete, visit your website at a URL like
http://demo-fastapi-97709018.azurewebsites.net/
,where the random number is your unique random number. You can find the website URL in the Azure portal or in the deployment logs if you forgot the number. - 🎉 Celebrate a successful deployment! You now have a URL that you can share with classmates, friends, and family.
You likely don't want to keep this particular website running forever in the cloud, so you should cleanup your Azure resources by destroying the resource group. You can do it in the Azure Cloud Shell by referencing the group name you created initially (demo-fastapi
in the examples):
az group delete --name demo-fastapi
When deploying, you might encounter errors or problems, either on the automation part of it (GitHub Actions) or on the deployment destination (Azure Web Apps).
You can check the logs of the Github Actions workflow by selecting the latest workflow from theActions tab. Find the first step that has a broken icon next to it, and expand that step to see what went wrong in it.
If running into trouble with the Azure deployment, check logs in the portal or use the following with the Azure CLI:
az webapp log tail --name $AZURE_WEBAPP_NAME --resource-group $AZURE_RESOURCE_GROUP
Update both variables to match your environment.
Help us make this template repository better byletting us know and opening an issue!.
About
Web API using FastAPI framework