Now that you have gained a bit of practical experience, it is time to fully understand
the syntax for workflows. Since workflows are written in YAML, it is important to
fully understand YAML before writing workflows.
What is YAML
YAML, which stands for "YAML Ain't Markup Language," is a data-serialization language optimized for human readability and writability. It's a strict superset of JSON but uses syntactically relevant newlines and indentation instead of braces.
YAML BASIC
To start, it’s essential to understand that YAML files have a .yml or .yaml extension, which makes them well-suited for version control systems like Git. This is because every change is tracked per line, allowing for efficient versioning.
# A full-line comment in YAML
key: value # An inline comment
Comments can appear anywhere in a line
Data Types :
Alright, here’s the same content in English:
In YAML, there are many data types, both primitive (simple scalars) and complex.
For example:
Scalar Types
In YAML, we can assign a value to a variable using this syntax:
key: value
Here, the key represents the variable name, and the value is its assigned type or value.
To get a better understanding of the context in a project, let's look at this example:
name: String
job: String
age: int
address:
- zip_code
- address_name
- numero
datetime: 1999-12-31T23:59:43.1Z
Note that keys and values in YAML can contain spaces and do not require quotation marks! You can use single or double quotes for keys and values, but this is only necessary if they contain special characters or if YAML might misinterpret their data type.
Double quotes (" ") use the backslash (\) as the escape character.
Single quotes (' ') use an additional single quote ('') for escaping.
There are cases when we want to write in multiple lines. In YAML syntax, this is done using the pipe operator and a four-space indentation, like in a literal block.
description: |
This is a description that spans multiple lines.
You can write as much as you want here,
and each new line will be preserved in the output.
- Lists can also be included within the block.
- Each line will start with an indentation.
This makes writing complex scripts in YAML workflows much easier than in other formats where you must quote variables
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Now that we've gotten a glimpse of what YAML can look like, let's return to some interesting topics.
Workflows
Now, we'll apply what we've learned so far in the context of GitHub Actions and build a foundation to tackle workflows.
The Workflow Syntax
As we know, the first element to start with when tackling a workflow in GitHub Action is the name element. A simple but important piece of information is that the name of the workflow can be different from the name of the file. For example, the file can be called main.yml, while the workflow is defined as follows:
name: My First Workflow
Events and Triggers
Events and triggers play a central role in building a robust workflow. Identifying when, or based on which events, to trigger the pipeline is a difficult decision to make.
In this section, GitHub Actions provides us with three main categories of triggers.
Webhook triggers
Scheduled triggers
Manual triggers
each triggers follow the key “on : “ in the workflow file
Webhook triggers
Here, webhook triggers work within the context of events in GitHub. For example:
Imagine you're working in a complex system with teammates from different team structures, and you want the workflow to start based on a webhook that triggers on a git push to the repository.
To achieve this, you can simply add this line of code in your workflow:
on: push
it can also be a pull request in the repo
on:[push,pull_request]
One of the nice features of webhook triggers is that they can be configured based on certain conditions. For example, you can start a workflow only when pushing to specific "branches" or when certain files in a path have been updated.
For example, in this scenario:
on:
push:
branches:
- main # Trigger only when pushing to the 'main' branch
paths:
- 'src/**' # Trigger only if files in the 'src/' directory have been modified
We only trigger the pipeline when changes are pushed to the "main" branch.
We also only trigger the workflow if files in the 'src/' directory have been modified.
These are just some examples of the most frequently used webhook triggers. You can also use many others, allowing you to customize your workflow to better fit your unique use case
Scheduled triggers
Here we have the schedule triggers. As the name suggests, these triggers start the workflow at a scheduled time—they use the same syntax as cron jobs. The syntax consists of five fields:
Minute (0-59)
Hour (0-23)
Day of month (1-31)
Month (1-12 or JAN-DEC)
Day of week (0-6 or SUN-SAT)
an example of a schedule trigger in a GitHub Actions workflow:
on:
schedule:
# Runs every 16th minute
- cron: '*/16 * * * *'
# Runs every hour from 10 AM to 3 PM
- cron: '0 10-15 * * *'
# Runs every Friday at midnight
- cron: '0 0 * * FRI'
# Runs every quarter (at 00:00 on day 1 of every 3rd month)
- cron: '0 0 1 */3 *'
As you can see here, we can combine multiple scheduling options in the same workflow, which can be helpful for running the workflow in batch mode
Manual Triggers
Finally, the last type is Manual Triggers. These allow you to start a workflow manually.
The syntax for a manual trigger can look like this:
on: workflow_dispatch
In this case, the trigger has one input: the branch the workflow runs on. The default branch is usually the main branch. You can use the GitHub UI to trigger the workflow manually, where you will be presented with a dialog to start the workflow."
You can also trigger the GitHub workflow using the GitHub CLI, either by name, ID, or relative file name to .github/workflows:
$ gh workflow run WORKFLOW_FILENAME
```"
Workflow jobs and steps
Here, the logic of the workflow is defined in the jobs section. As we know, each job is executed on a runner. The runner can either be self-hosted, or you can choose one from the cloud.
Make sure to use the latest version of the runner, such as ubuntu-latest, windows-latest, or macos-latest, but always remember the cost factor.
Operating System
Price
Linux
$0.008
macOS
$0.08
Windows
$0.016
Workflow jobs
As we defined previously, jobs are the units of work here; they run in parallel by default.
You can chain them in a sequence by having a job depend on the successful output of one or multiple other jobs using the needs keyword
Q- now given all the context so far using this tech stack
Q- fast api ,
Q- try to build a simple proof of concpect workflow that implemenethe most frequent concept here
Q- make as simple by simple detail tutor from thr creation of the github repo
Q- until bulding the simple data modle and rest api
Q- then update the code bu adding a field and change the method
Q- and this push the update code
Q- and make the github action trigger the full workflow okii
Q-make it details one oki
Sure! Let's build a simple proof-of-concept (PoC) workflow using FastAPI and GitHub Actions. This tutorial will guide you step-by-step from creating a GitHub repository to setting up a FastAPI application, updating it, and configuring a GitHub Actions workflow to automate tasks upon code changes.
Create a Virtual Environment (optional but recommended):
python -m venv venv
Activate the Virtual Environment:
Windows:
venv\Scripts\activate
macOS/Linux:
source venv/bin/activate
Install FastAPI and Uvicorn:
pip install fastapi uvicorn
b. Creating the Data Model and REST API
Create main.py in the root directory:
touch main.py
Edit main.py with the following content:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
# Data Model
class Item(BaseModel):
id: int
name: str
description: str
# In-memory "database"
items: List[Item] = []
# Create an item
@app.post("/items/", response_model=Item)
def create_item(item: Item):
items.append(item)
return item
# Read all items
@app.get("/items/", response_model=List[Item])
def read_items():
return items
Explanation:
Data Model: Defines an Item with id, name, and description.
Endpoints:
POST /items/: Create a new item.
GET /items/: Retrieve all items.
4. Creating requirements.txt
To specify project dependencies, create a requirements.txt file.
Create requirements.txt:
touch requirements.txt
Add Dependencies:
fastapi
uvicorn
Later Dependencies: As you expand your project, remember to update this file.
5. Building the GitHub Actions Workflow
GitHub Actions will help automate testing, deployment, or other tasks whenever specific events occur in your repository.
a. Understanding Workflow Structure
A GitHub Actions workflow is defined in YAML and consists of:
name: The name of the workflow.
on: The events that trigger the workflow.
jobs: A set of jobs to run, each with its own steps.
runs-on: The type of runner (e.g., ubuntu-latest).
steps: Individual tasks within a job, such as checking out code, setting up Python, installing dependencies, and running tests.
b. Writing the Workflow YAML File
Create Directory for Workflows:
GitHub Actions workflows are stored in .github/workflows/.
mkdir -p .github/workflows
Create Workflow File:
Let's name it ci.yml.
touch .github/workflows/ci.yml
Edit ci.yml with the following content:
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run FastAPI (simple test)
run: |
uvicorn main:app --host 0.0.0.0 --port 8000 &
sleep 3
curl http://localhost:8000/items/
Explanation:
name: CI (Continuous Integration workflow).
on:
Triggers on push and pull_request events to the main branch.
jobs:
build:
runs-on: Uses the latest Ubuntu runner.
steps:
Checkout: Retrieves the repository's code.
Set up Python: Sets Python version to 3.9.
Install dependencies: Installs packages from requirements.txt.
Run FastAPI (simple test):
Starts the FastAPI server.
Waits for 3 seconds to ensure the server is up.
Uses curl to make a GET request to /items/ endpoint.
Note: This is a basic test to ensure the FastAPI server starts without errors. For more robust testing, consider adding automated tests using frameworks like pytest.
6. Pushing Initial Code to GitHub
Stage the Changes:
git add .
Commit the Changes:
git commit -m "Initial commit: Set up FastAPI project and CI workflow"
Push to GitHub:
git push origin main
GitHub Actions Trigger:
Upon pushing, the workflow defined in ci.yml will automatically trigger.
7. Updating the FastAPI Application
Let's simulate updating the application by adding a new field to the Item model and modifying an existing method.
a. Adding a New Field
Edit main.py to add a price field:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
# Updated Data Model with 'price'
class Item(BaseModel):
id: int
name: str
description: str
price: float # New field
# In-memory "database"
items: List[Item] = []
# Create an item
@app.post("/items/", response_model=Item)
def create_item(item: Item):
items.append(item)
return item
# Read all items
@app.get("/items/", response_model=List[Item])
def read_items():
return items
Explanation:
Added a new field price of type float to the Item model.
b. Changing an Existing Method
Let's modify the read_items method to filter items based on a minimum price.
Update read_items in main.py:
from fastapi import FastAPI, Query
# ... (previous code remains unchanged)
# Read items with optional minimum price filter
@app.get("/items/", response_model=List[Item])
def read_items(min_price: float = Query(0.0, ge=0.0)):
return [item for item in items if item.price >= min_price]
Explanation:
Added a query parameter min_price with a default value of 0.0.
Filters the returned items to include only those with a price greater than or equal to min_price.
8. Pushing Updates and Triggering GitHub Actions
Stage the Changes:
git add main.py
Commit the Changes:
git commit -m "Update Item model with 'price' field and filter in read_items method"
Push to GitHub:
git push origin main
GitHub Actions Trigger:
The push will trigger the CI workflow defined in ci.yml.