GithubHelp home page GithubHelp logo

rohity24 / codespaces-project-template-py Goto Github PK

View Code? Open in Web Editor NEW

This project forked from education/codespaces-project-template-py

0.0 0.0 0.0 243 KB

Codespaces template for building a Python project

License: MIT License

Python 28.18% HTML 55.68% Dockerfile 16.15%

codespaces-project-template-py's Introduction

Open in GitHub Codespaces

Python HTTP API for use with GitHub Codespaces

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 the FastAPI framework. You'll get to focus on working with the project instead of setup and configuration.

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 computer and receive a response. For example, my computer could send a request to http://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 share with other computers. In this project, you'll run an HTTP API that generates a random token.

Running FastAPI

This template is also ready to be used with Codespaces, a developer environment running in the cloud with Visual Studio Code.

๐ŸŽฅ Watch the video tutorial to learn more about Codespaces

Codespaces Tutorial

For students and developers

Using Codespaces, you get Visual Studio Code in the cloud, using a "developer container". Like a locally running version of Visual Studio Code, the cloud version also allows you to install extensions and use a terminal.

You can also configure your developer 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:

๐Ÿง Try it out

Try out this template repository using Codespaces following these steps:

  1. Create a repository from this template. Use this create repo link. You can make the repository private or public, up to you.
  2. Navigate to the main page of the newly created repository.
  3. Under the repository name, use the Code drop-down menu, and in the Codespaces tab, select "Create Codespace on main". Create Codespace
  4. Wait as Github initializes the codespace: Creating Codespace

Inspect your Codespaces environment

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.

Running the App

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:

  1. 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.

  2. 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.

  3. Once the site loads, click on the Try it Out button or append /docs to the URL in the address bar. The automatically generated API documentation should load and look like this:

    OpenAPI docs

  4. Finally, try to interact with the API by sending a request using the self-documented page. Click on the POST button and then on the Try it Out button:

    Try a POST request

๐Ÿ”’ 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).

Customize the Codespace

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:

  1. Changing the Python version
  2. Adding or modifying a pre-installed editor extension

Step 1: Change the Python environment

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 in devcontainer.json, a box will appear after saving.

Recreating Codespace

Click on rebuild. Wait for your Codespace to rebuild the VS Code environment.

Step 2: Add an extension

Your environment comes with pre-installed extensions. You can change which extensions your Codespaces environment starts with. Here's how:

  1. Open file .devcontainer/devcontainer.json and locate the following JSON element extensions:

    "extensions": [
     "ms-python.python",
     "ms-python.vscode-pylance"
    ]
  2. 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 of Black 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.

    Recreating Codespace

    Click on rebuild. Wait for your Codespace to rebuild the VS Code environment.

To find the unique identifier of an extension:

๐Ÿš€ Next steps

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:

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.

  1. Open the Azure Cloud Shell.
  2. Use the Bash shell (not PowerShell!) for these steps.
  3. 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.
  4. Create a Resource Group which will group together the different Azure resources used for the app:
az group create --name demo-fastapi --location "East US"
  1. You'll see a JSON response with details about the newly created resource, for this command and all the commands that follow.
  2. Create the FREE App Service Plan:
az appservice plan create --name "demo-fastapi" --resource-group demo-fastapi --is-linux --sku FREE
  1. Create a random identifier for a unique webapp name:
let "randomIdentifier=$RANDOM*$RANDOM"
  1. Create the Web 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"
  1. Head to the Azure portal App 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:

  1. Find the ID of your Azure Subscription in the Azure portal or by following this guide.
  2. 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 --name "CICD" --role contributor --scopes /subscriptions/$AZURE_SUBSCRIPTION_ID --sdk-auth
  1. Capture the output and add it as a Github repository secret with the name AZURE_CREDENTIALS.
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.

  1. 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.
  2. Open the .github/workflows/web_app.yml file and update the value of AZURE_WEBAPP_NAME to your app name.
๐Ÿƒ Deploy your app!

Before continuing, check the following:

  1. You've created an Azure Service Principal and saved it as a repository secret as AZURE_CREDENTIALS.
  2. You've created an App Service with a valid name and the site is already available with the default static content.

To deploy:

  1. Go to repository actions and click on Run workflow and then the green button to run it.

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

Destroy resources when complete

After deploying, make sure you cleanup your 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

Deployment Troubleshooting

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).

If running into trouble, 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.

Other Resources

๐Ÿ”Ž Found an issue or have an idea for improvement?

Help us make this template repository better by letting us know and opening an issue!.

codespaces-project-template-py's People

Contributors

abrilurena avatar alfredodeza avatar microsoft-github-operations[bot] avatar microsoftopensource avatar pablonunes avatar pamelafox avatar softchris avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.