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.
yaml
# 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:
yaml
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:
yaml
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.
yaml
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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
When defining complex data types, YAML provides two types of collections: maps and lists (also known as sequences).
Maps
Maps use two spaces of indentation with the same syntax as assigning variables:
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:
yaml
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:
yaml
on: push
it can also be a pull request in the repo
yaml
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:
yaml
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:
yaml
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:
yaml
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:
bash
$ 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 create a detailed, step-by-step tutorial to build a simple FastAPI application, set up a GitHub repository, implement a GitHub Actions workflow, and demonstrate how pushing code updates triggers the workflow. This tutorial will guide you from creating the repository to developing the API, setting up continuous integration, and making code updates that trigger the workflow.
Note: If the default branch is master, adjust the command accordingly.
Verify on GitHub:
Go to your GitHub repository page to ensure all files are uploaded.
Step 5: Set Up GitHub Actions Workflow
GitHub Actions allows you to automate tasks within your software development lifecycle. We'll set up a simple workflow that installs dependencies and runs tests whenever code is pushed to the repository.
5.1: Create the Workflow Directory
Create .github/workflows Directory:
bash
mkdir -p .github/workflows
5.2: Add a Workflow YAML File
Create ci.yml:
bash
touch .github/workflows/ci.yml
Open ci.yml in Your Editor and Add the Following Content:
yaml
name: CI Pipeline
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 Tests
run: |
# For demonstration, we'll perform a simple test
# In a real project, implement proper unit tests
python -c "import app.main; print('Tests Passed')"
Explanation of the Workflow:
Name:CI Pipeline
Triggers:
On Push: To the main branch.
On Pull Request: Targeting the main branch.
Jobs:
Build Job:
runs-on: Uses the latest Ubuntu runner.
Steps:
Checkout Repository: Uses actions/checkout@v3 to clone the repo.
Set Up Python: Uses actions/setup-python@v4 to set up Python 3.9.
Install Dependencies: Upgrades pip and installs dependencies from requirements.txt.
Executes a simple Python command to simulate tests.
5.3: Enhancing the Workflow with Actual Tests
For a more realistic scenario, let's add a simple test using pytest.
Now, we'll make an update to the FastAPI application by adding a new field to the Item model and modifying an endpoint. This change will trigger the GitHub Actions workflow upon pushing the update.
6.1: Modify the Data Model and Endpoint
Open app/main.py and Update the Item Model:
python
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional # Import Optional
app = FastAPI()
# Updated Data Model with an optional 'price' field
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
price: float = 0.0 # New field added
# In-memory "database"
items_db: List[Item] = []
# Create an item
@app.post("/items/", response_model=Item)
def create_item(item: Item):
items_db.append(item)
return item
# Read all items
@app.get("/items/", response_model=List[Item])
def read_items():
return items_db
# Read item by ID
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
for item in items_db:
if item.id == item_id:
return item
return {"error": "Item not found"}
# Update item
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, updated_item: Item):
for index, item in enumerate(items_db):
if item.id == item_id:
items_db[index] = updated_item
return updated_item
return {"error": "Item not found"}
# Delete item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
for index, item in enumerate(items_db):
if item.id == item_id:
del items_db[index]
return {"message": "Item deleted"}
return {"error": "Item not found"}
Update the Test to Reflect the Change:
Modify :
6.2: Making a Code Change and Pushing
For demonstration, let's intentionally introduce a failing test to see how the workflow handles it.
Introduce an Error in app/main.py:
Change the price field default from 0.0 to a string 'free':
python
# ...
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
price: str = 'free' # Changed from float to str
# ...
During the "Run Tests" step, pytest will execute the tests.
The test_create_item will fail because it's expecting price to be a float.
Check Workflow Status:
The workflow will show as "Failed".
Click on the workflow run to see detailed logs and identify the failing test.
Revert the Error:
Modify app/main.py Back to Correct Type:
python
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
price: float = 0.0 # Reverted to float
Commit and Push the Fix:
bash
git add app/main.py
git commit -m "Fix price field type to float"
git push
Verify Workflow Success:
The workflow should pass after fixing the error.
Conclusion
Congratulations! You've successfully:
Created a GitHub Repository: Initialized and set up a remote repository for your project.
Set Up a FastAPI Project: Developed a simple FastAPI application with CRUD operations.
Implemented GitHub Actions Workflow: Set up a CI pipeline that automatically runs tests on code pushes and pull requests.
Demonstrated Workflow Triggers: Made code changes that triggered the workflow, including handling both successful and failed test scenarios.
This setup forms a solid foundation for developing robust applications with automated testing and continuous integration using GitHub Actions. You can further enhance this workflow by adding more comprehensive tests, integrating deployment steps, linting, code coverage reports, and more based on your project's requirements.