<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Emmanuel Adebiyi]]></title><description><![CDATA[Emmanuel Adebiyi]]></description><link>https://biyiemmy.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 22:03:44 GMT</lastBuildDate><atom:link href="https://biyiemmy.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How I Would Build a FastAPI and MySQL REST API from Scratch Again]]></title><description><![CDATA[Learn how to build a FastAPI REST API with MySQL and SQLAlchemy: connect the database, create a model and schema, and handle 404 errors.]]></description><link>https://biyiemmy.hashnode.dev/how-i-would-build-a-fastapi-and-mysql-rest-api-from-scratch-again</link><guid isPermaLink="true">https://biyiemmy.hashnode.dev/how-i-would-build-a-fastapi-and-mysql-rest-api-from-scratch-again</guid><category><![CDATA[Python]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[sqlalchemy]]></category><category><![CDATA[REST API]]></category><category><![CDATA[FastAPI]]></category><dc:creator><![CDATA[Emmanuel Adebiyi]]></dc:creator><pubDate>Thu, 03 Dec 2026 01:26:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/feb797c1-71a8-49d5-8ec5-6fbd08838353.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This project started as an in-class task: build a Customers API with FastAPI that retrieves all customers from a MySQL database, returns one customer by ID, and responds with a <code>404 Not Found</code> when the customer doesn't exist.</p>
<p>To be frank, I struggled with it in class. My problem was not one particular error. It was knowing how to approach the task: where to start, what to build first, and how to break it into steps I could finish one at a time.</p>
<p>So this article is the approach I would take if the task were handed to me again. It isn't a polished expert tutorial. It's a sequence of small steps, each with a reason for coming before the next: set up the project, create the database, connect to it, define the model and the response schema, create the table, write the endpoints, and test in Swagger UI.</p>
<p>By the end you will have a FastAPI app connected to MySQL through SQLAlchemy, with <code>GET /customers</code> and <code>GET /customers/{customer_id}</code>.</p>
<h2>Project Overview</h2>
<p>The application connects a FastAPI backend to a MySQL database containing customer records.</p>
<p>It provides two GET endpoints:</p>
<ul>
<li><code>GET /customers</code> – Retrieves all customers from the database.</li>
<li><code>GET /customers/{customer_id}</code> – Retrieves a specific customer using their ID.</li>
</ul>
<p>If a customer with the requested ID does not exist, the API returns a <code>404 Not Found</code> response.</p>
<h3>Technologies Used</h3>
<p>Here are the main technologies and libraries used:</p>
<ul>
<li><strong>Python:</strong> The programming language used to build the application.</li>
<li><strong>FastAPI:</strong> A Python web framework for building the REST API.</li>
<li><strong>MySQL:</strong> The relational database used to store customer information.</li>
<li><strong>SQLAlchemy:</strong> The Object Relational Mapper (ORM) used to interact with MySQL.</li>
<li><strong>PyMySQL:</strong> The database driver that allows SQLAlchemy to communicate with MySQL.</li>
<li><strong>Pydantic:</strong> Used for defining and validating API response data.</li>
<li><strong>Uvicorn:</strong> The ASGI server used to run the application.</li>
<li><strong>python-dotenv:</strong> Used to load database configuration from environment variables.</li>
</ul>
<h2>1. Setting Up the Project</h2>
<p>I started by creating a project directory and setting up a Python virtual environment to keep the project's dependencies isolated.</p>
<pre><code class="language-bash">mkdir customers-api
cd customers-api

python3 -m venv .venv
source .venv/bin/activate
</code></pre>
<p>Next, I installed the required packages:</p>
<pre><code class="language-bash">pip install fastapi uvicorn sqlalchemy pymysql python-dotenv
</code></pre>
<p>After installing the dependencies, I generated a <code>requirements.txt</code> file:</p>
<pre><code class="language-bash">pip freeze &gt; requirements.txt
</code></pre>
<p>This file records the installed dependencies, making it easier to recreate the development environment on another machine.</p>
<h2>2. Creating the MySQL Database</h2>
<p>The next step was to create a database for storing customer records.</p>
<p>I used MySQL Workbench to create a database named <code>customers_db</code>.</p>
<pre><code class="language-sql">CREATE DATABASE customers_db;
</code></pre>
<p>The database contains a table named <code>customers</code> with the following fields:</p>
<table>
<thead>
<tr>
<th>Column</th>
<th>Data Type</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>id</td>
<td>INT</td>
<td>Primary key with auto-increment</td>
</tr>
<tr>
<td>name</td>
<td>VARCHAR(150)</td>
<td>Customer's full name</td>
</tr>
<tr>
<td>email</td>
<td>VARCHAR(150)</td>
<td>Customer's email address</td>
</tr>
<tr>
<td>phone</td>
<td>VARCHAR(20)</td>
<td>Customer's phone number</td>
</tr>
<tr>
<td>city</td>
<td>VARCHAR(150)</td>
<td>Customer's city</td>
</tr>
</tbody></table>
<p>The <code>name</code> and <code>email</code> fields are required, while <code>phone</code> and <code>city</code> are optional.</p>
<p>I also inserted five sample customer records into the table to provide data for testing the API endpoints.</p>
<h2>3. Configuring the Database Connection</h2>
<p>To keep the database configuration separate from the application logic, I created a <code>.env</code> file in the project root directory.</p>
<pre><code class="language-env">DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
DB_NAME=customers_db
</code></pre>
<p>The <code>.env</code> file contains the database connection details. It is excluded from version control through <code>.gitignore</code> to prevent credentials from being uploaded to GitHub.</p>
<p>I then created <code>database.py</code> to establish the connection between FastAPI and MySQL.</p>
<pre><code class="language-python">import os

from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

load_dotenv()

DB_HOST = os.getenv("DB_HOST")
DB_PORT = os.getenv("DB_PORT")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_NAME = os.getenv("DB_NAME")

DATABASE_URL = (
    f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}"
    f"@{DB_HOST}:{DB_PORT}/{DB_NAME}"
)

engine = create_engine(DATABASE_URL)

SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine
)

Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
</code></pre>
<p>Let's look at some important parts of this file.</p>
<p><strong>Loading environment variables</strong></p>
<pre><code class="language-python">load_dotenv()
</code></pre>
<p>This loads the variables defined in the <code>.env</code> file so they can be accessed using <code>os.getenv()</code>.</p>
<p><strong>Creating the database engine</strong></p>
<pre><code class="language-python">engine = create_engine(DATABASE_URL)
</code></pre>
<p>The SQLAlchemy engine manages the connection between the application and the MySQL database.</p>
<p><strong>Creating database sessions</strong></p>
<pre><code class="language-python">SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine
)
</code></pre>
<p>This creates a session factory. The application uses it to create database sessions when it needs to execute queries.</p>
<p><strong>Managing database sessions</strong></p>
<pre><code class="language-python">def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
</code></pre>
<p>The <code>get_db()</code> function provides a database session to API endpoints. The <code>yield</code> statement allows FastAPI to use the session during the request, while the <code>finally</code> block ensures that it is closed afterward.</p>
<p>This helps prevent database sessions from remaining open unnecessarily.</p>
<h2>4. Creating the Customer Model</h2>
<p>With the database connection configured, I created <code>models.py</code>.</p>
<p>This file defines the structure of the customer table using SQLAlchemy.</p>
<pre><code class="language-python">from sqlalchemy import Column, Integer, String
from database import Base


class Customer(Base):
    __tablename__ = "customers"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(150), nullable=False)
    email = Column(String(150), nullable=False)
    phone = Column(String(20), nullable=True)
    city = Column(String(150), nullable=True)
</code></pre>
<p>The <code>Customer</code> class represents the <code>customers</code> table in MySQL.</p>
<p>Here's what the declarations mean:</p>
<ul>
<li><code>__tablename__ = "customers"</code> specifies the database table name.</li>
<li><code>id</code> is an integer primary key and is indexed.</li>
<li><code>name</code> and <code>email</code> are required fields because <code>nullable=False</code>.</li>
<li><code>phone</code> and <code>city</code> are optional because <code>nullable=True</code>.</li>
</ul>
<p>Using SQLAlchemy models allows me to work with database records through Python classes instead of writing raw SQL queries for every operation.</p>
<h2>5. Creating the Pydantic Response Schema</h2>
<p>Next, I created <code>schemas.py</code> to define the structure of the data returned by the API.</p>
<pre><code class="language-python">from pydantic import BaseModel, ConfigDict


class CustomerOut(BaseModel):
    id: int
    name: str
    email: str
    phone: str | None = None
    city: str | None = None

    model_config = ConfigDict(from_attributes=True)
</code></pre>
<p>The <code>CustomerOut</code> schema defines the fields that should appear in the API response.</p>
<p>One important configuration here is:</p>
<pre><code class="language-python">model_config = ConfigDict(from_attributes=True)
</code></pre>
<p>This tells Pydantic that it can read values directly from object attributes, including SQLAlchemy model instances.</p>
<p>Without this configuration, Pydantic would not automatically validate the returned SQLAlchemy objects in this manner.</p>
<p>Separating the database model from the response schema also makes it easier to control what information the API exposes.</p>
<h2>6. Creating the Database Table</h2>
<p>I created a separate file named <code>create_tables.py</code> to generate the database table from the SQLAlchemy model.</p>
<pre><code class="language-python">from database import Base, engine
from models import Customer

Base.metadata.create_all(bind=engine)

print("Customers table created successfully!")
</code></pre>
<p>The <code>Base.metadata.create_all()</code> method checks the registered SQLAlchemy models and creates their corresponding tables if they do not already exist.</p>
<p>I ran the script using:</p>
<pre><code class="language-bash">python create_tables.py
</code></pre>
<p>After execution, I verified the table structure in MySQL Workbench using:</p>
<pre><code class="language-sql">DESCRIBE customers;
</code></pre>
<p>This confirmed that the table contained the expected columns and data types.</p>
<h2>7. Building the API Endpoints</h2>
<p>With the database, model, and schema ready, I moved on to <code>main.py</code>, where I implemented the API endpoints.</p>
<p>First, I imported the necessary modules and initialized the FastAPI application.</p>
<pre><code class="language-python">from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

import models
import schemas
from database import engine, get_db

models.Base.metadata.create_all(bind=engine)

app = FastAPI(title="Customers API")
</code></pre>
<p>The <code>FastAPI()</code> instance creates the application.</p>
<p>The <code>models.Base.metadata.create_all(bind=engine)</code> statement also ensures that the registered database tables exist when the application starts.</p>
<h3>Endpoint 1: Retrieve All Customers</h3>
<p>The first endpoint retrieves every customer record from the database.</p>
<pre><code class="language-python">@app.get("/customers", response_model=list[schemas.CustomerOut])
def get_customers(db: Session = Depends(get_db)):
    customers = db.query(models.Customer).all()
    return customers
</code></pre>
<p>Let's break down how it works.</p>
<p><strong>Route declaration</strong></p>
<pre><code class="language-python">@app.get("/customers")
</code></pre>
<p>This registers a GET endpoint at <code>/customers</code>.</p>
<p><strong>Response model</strong></p>
<pre><code class="language-python">response_model=list[schemas.CustomerOut]
</code></pre>
<p>This tells FastAPI to validate and serialize the returned data as a list of <code>CustomerOut</code> objects.</p>
<p><strong>Database dependency</strong></p>
<pre><code class="language-python">db: Session = Depends(get_db)
</code></pre>
<p>FastAPI uses dependency injection to provide the database session returned by <code>get_db()</code>.</p>
<p><strong>Database query</strong></p>
<pre><code class="language-python">customers = db.query(models.Customer).all()
</code></pre>
<p>This SQLAlchemy query retrieves all records from the <code>customers</code> table.</p>
<p>Finally, the function returns the results, which FastAPI serializes into JSON.</p>
<h3>Endpoint 2: Retrieve a Customer by ID</h3>
<p>The second endpoint retrieves one customer using their unique ID.</p>
<pre><code class="language-python">@app.get("/customers/{customer_id}", response_model=schemas.CustomerOut)
def get_customer(customer_id: int, db: Session = Depends(get_db)):
    customer = db.query(models.Customer).filter(
        models.Customer.id == customer_id
    ).first()

    if customer is None:
        raise HTTPException(
            status_code=404,
            detail="Customer not found"
        )

    return customer
</code></pre>
<p>The endpoint accepts a <code>customer_id</code> as a path parameter.</p>
<p>For example:</p>
<pre><code class="language-text">GET /customers/1
</code></pre>
<p>The database query filters the customer records by ID:</p>
<pre><code class="language-python">db.query(models.Customer).filter(
    models.Customer.id == customer_id
).first()
</code></pre>
<p>The <code>.first()</code> method returns the first matching record or <code>None</code> if no matching record exists.</p>
<p>To handle missing records, I used FastAPI's <code>HTTPException</code>:</p>
<pre><code class="language-python">if customer is None:
    raise HTTPException(
        status_code=404,
        detail="Customer not found"
    )
</code></pre>
<p>This ensures that the API returns a meaningful <code>404 Not Found</code> response instead of returning an empty result or an unexpected server error.</p>
<p>The complete <code>main.py</code> implementation is:</p>
<pre><code class="language-python">from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

import models
import schemas
from database import engine, get_db

models.Base.metadata.create_all(bind=engine)

app = FastAPI(title="Customers API")


@app.get("/customers", response_model=list[schemas.CustomerOut])
def get_customers(db: Session = Depends(get_db)):
    customers = db.query(models.Customer).all()
    return customers


@app.get("/customers/{customer_id}", response_model=schemas.CustomerOut)
def get_customer(customer_id: int, db: Session = Depends(get_db)):
    customer = db.query(models.Customer).filter(
        models.Customer.id == customer_id
    ).first()

    if customer is None:
        raise HTTPException(
            status_code=404,
            detail="Customer not found"
        )

    return customer
</code></pre>
<h2>8. Running the Application</h2>
<p>After implementing the endpoints, I started the application using Uvicorn:</p>
<pre><code class="language-bash">uvicorn main:app --reload
</code></pre>
<p>The <code>--reload</code> option automatically restarts the development server when code changes are detected.</p>
<p>Once the server started successfully, I accessed the interactive API documentation at:</p>
<pre><code class="language-text">http://127.0.0.1:8000/docs
</code></pre>
<p>FastAPI automatically generated the Swagger UI documentation, allowing me to inspect and execute the available endpoints directly from the browser.</p>
<h2>9. Testing the API</h2>
<p>I used Swagger UI to test both endpoints and verify how the API handled successful and unsuccessful requests.</p>
<p>Three test cases were performed.</p>
<h3>Test 1: Retrieve All Customers</h3>
<p>I expanded the <code>GET /customers</code> endpoint, clicked <strong>Try it out</strong>, and executed the request.</p>
<p>The API returned a <code>200 OK</code> status code and a JSON array containing all five customer records.</p>
<pre><code class="language-json">[
  {
    "id": 1,
    "name": "John Smith",
    "email": "john.smith@example.com",
    "phone": "08012345678",
    "city": "Lagos"
  },
  {
    "id": 2,
    "name": "Sarah Johnson",
    "email": "sarah.j@example.com",
    "phone": "08023456789",
    "city": "Abuja"
  },
  {
    "id": 3,
    "name": "Michael Brown",
    "email": "michael.b@example.com",
    "phone": "08034567890",
    "city": "Ibadan"
  },
  {
    "id": 4,
    "name": "Grace Williams",
    "email": "grace.w@example.com",
    "phone": "08045678901",
    "city": "Port Harcourt"
  },
  {
    "id": 5,
    "name": "Pamilerin Wilson",
    "email": "david.w@example.com",
    "phone": "08056789012",
    "city": "Kano"
  }
]
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/5211ad91-d5c9-49d8-ad73-4febadab8c71.png" alt="" style="display:block;margin:0 auto" />

<p>This confirmed that the application could successfully connect to MySQL and retrieve all customer records.</p>
<h3>Test 2: Retrieve a Single Customer</h3>
<p>Next, I tested the <code>GET /customers/{customer_id}</code> endpoint using the customer ID <code>1</code>.</p>
<p>The request was:</p>
<pre><code class="language-http">GET /customers/1
</code></pre>
<p>The API returned a <code>200 OK</code> response containing the details of the matching customer.</p>
<pre><code class="language-json">{
  "id": 1,
  "name": "John Smith",
  "email": "john.smith@example.com",
  "phone": "08012345678",
  "city": "Lagos"
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/e4e0d1ea-4b49-4b15-b8a6-4ddf44bd6cb9.png" alt="" style="display:block;margin:0 auto" />

<p>This confirmed that the API could retrieve an individual customer using a path parameter.</p>
<h3>Test 3: Retrieve a Non-existent Customer</h3>
<p>Finally, I tested the endpoint using customer ID <code>99</code>, which does not exist in the database.</p>
<p>The request was:</p>
<pre><code class="language-http">GET /customers/99
</code></pre>
<p>Instead of returning a customer record, the API correctly returned a <code>404 Not Found</code> response.</p>
<pre><code class="language-json">{
  "detail": "Customer not found"
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/ea3f8d76-ccbe-4a70-9a00-76a10b593926.png" alt="" style="display:block;margin:0 auto" />

<p>This confirmed that the error-handling logic was working as expected.</p>
<h3>Test Results Summary</h3>
<table>
<thead>
<tr>
<th>Test Case</th>
<th>Expected Result</th>
<th>Actual Result</th>
</tr>
</thead>
<tbody><tr>
<td>Retrieve all customers</td>
<td>200 OK</td>
<td>Passed</td>
</tr>
<tr>
<td>Retrieve customer with ID 1</td>
<td>200 OK</td>
<td>Passed</td>
</tr>
<tr>
<td>Retrieve non-existent customer with ID 99</td>
<td>404 Not Found</td>
<td>Passed</td>
</tr>
</tbody></table>
<p>All three test cases produced the expected results.</p>
<h2>10. Project Structure</h2>
<p>The final project structure is:</p>
<pre><code class="language-text">customers-api/
│
├── .gitignore
├── create_tables.py
├── database.py
├── main.py
├── models.py
├── requirements.txt
├── schemas.py
├── README.md
│
└── screenshots/
    ├── get-all-customers.png
    ├── get-customer-by-id.png
    └── customer-not-found.png
</code></pre>
<p>The application files are separated according to their responsibilities:</p>
<ul>
<li><code>main.py</code> – Defines the FastAPI application and API endpoints.</li>
<li><code>database.py</code> – Handles database configuration and session management.</li>
<li><code>models.py</code> – Defines the SQLAlchemy customer model.</li>
<li><code>schemas.py</code> – Defines the Pydantic response schema.</li>
<li><code>create_tables.py</code> – Creates the database tables.</li>
<li><code>requirements.txt</code> – Lists the project dependencies.</li>
<li><code>.env</code> – Stores local database configuration and is excluded from Git.</li>
<li><code>.gitignore</code> – Specifies files and directories Git should ignore.</li>
<li><code>screenshots/</code> – Contains screenshots of the API tests.</li>
</ul>
<h2>11. What I Learned</h2>
<p>Working on this project helped me understand how the different components of a backend application work together.</p>
<p>Some of my key takeaways include:</p>
<ol>
<li><strong>Database integration:</strong> How to connect a FastAPI application to a MySQL database using SQLAlchemy and PyMySQL.</li>
<li><strong>Object Relational Mapping:</strong> How SQLAlchemy models represent database tables and allow database queries through Python.</li>
<li><strong>Pydantic schemas:</strong> How to define response structures and serialize SQLAlchemy objects using <code>from_attributes=True</code>.</li>
<li><strong>Dependency injection:</strong> How FastAPI provides database sessions to endpoint functions using <code>Depends()</code>.</li>
<li><strong>HTTP status codes:</strong> How to return appropriate responses, particularly <code>200 OK</code> and <code>404 Not Found</code>.</li>
<li><strong>API testing:</strong> How to use Swagger UI to execute requests and verify API responses.</li>
</ol>
<h2>12. Possible Improvements</h2>
<p>This project currently focuses on retrieving customer records. There are several ways it could be extended:</p>
<ul>
<li>Add a POST endpoint to create new customers.</li>
<li>Add PUT and PATCH endpoints to update customer information.</li>
<li>Add a DELETE endpoint to remove customer records.</li>
<li>Implement pagination when retrieving large customer datasets.</li>
<li>Add input validation for customer information.</li>
<li>Introduce automated API tests using Pytest.</li>
<li>Use database migrations with Alembic instead of relying on <code>create_all()</code> for schema changes.</li>
<li>Add authentication and authorization.</li>
</ul>
<p>These improvements would help turn the application into a more complete customer management API.</p>
<h2>Conclusion</h2>
<p>Building this Customers REST API was a useful hands-on exercise in backend development with Python.</p>
<p>It brought together FastAPI, SQLAlchemy, MySQL, and Pydantic to create an application that retrieves database records through HTTP endpoints and handles missing records appropriately.</p>
<p>More importantly, it helped me understand how database models, response schemas, database sessions, and API routes fit together in a working backend application.</p>
<p>This project is a foundation for building more advanced REST APIs with additional functionality and more complex database operations.</p>
<h2>Source Code</h2>
<p>The complete source code, project setup instructions, and screenshots are available on GitHub:</p>
<p><a href="https://github.com/biyiemmy/customers-api"><strong>View the Customers API repository</strong></a></p>
<p>Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[How I Built an Inventory Management Database with MySQL as a Beginner]]></title><description><![CDATA[Learn MySQL basics by building an inventory database for a fictional Nigerian store: create, insert, select, filter, sort, update and delete.]]></description><link>https://biyiemmy.hashnode.dev/how-i-built-an-inventory-management-database-with-mysql-as-a-beginner</link><guid isPermaLink="true">https://biyiemmy.hashnode.dev/how-i-built-an-inventory-management-database-with-mysql-as-a-beginner</guid><category><![CDATA[MySQL]]></category><category><![CDATA[SQL]]></category><category><![CDATA[database]]></category><category><![CDATA[Beginners, Tutorial]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Emmanuel Adebiyi]]></dc:creator><pubDate>Tue, 01 Dec 2026 22:58:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/c21d1b0d-bb9d-418b-9299-935824a807f8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>As an AI engineering student at Publica Academy, one of my assignments was to build and manage a database using SQL. The task was to design a products table, load it with sample data, and then practise the core operations: retrieving, filtering, sorting, updating and deleting records. It made sense to me, because almost every AI system sits on top of stored data, and I wanted to be comfortable working with that data before building anything on top of it.</p>
<p>The scenario was NaijaMart, a fictional Nigerian store that sells everyday foodstuffs like rice, garri, yam and palm oil. Any business that sells products needs to know what is in stock, what each item costs, and what is running low, so an inventory database was a natural fit.</p>
<p>Getting MySQL running on my Mac was my first real challenge. The server refused to start until I discovered that two separate installations were competing for the same port, and it taught me to read the error log before changing anything.</p>
<p>In this article I walk through everything I built in MySQL: creating the database and a table, inserting 15 products, then retrieving, filtering, sorting, updating and deleting records. I wrote every statement directly in MySQL Workbench, with no application or API in between, so the focus stays on SQL itself.</p>
<p>You can find the full script on GitHub: <a href="https://github.com/biyiemmy/naijamart-inventory-management">https://github.com/biyiemmy/naijamart-inventory-management</a></p>
<h2>Project Objectives</h2>
<p>The project was designed to demonstrate the following:</p>
<ul>
<li>Creating and selecting a MySQL database.</li>
<li>Designing a table with appropriate data types and constraints.</li>
<li>Inserting product records into a database.</li>
<li>Retrieving records using <code>SELECT</code>.</li>
<li>Filtering data using <code>WHERE</code>.</li>
<li>Sorting records using <code>ORDER BY</code>.</li>
<li>Limiting query results using <code>LIMIT</code>.</li>
<li>Updating existing records using <code>UPDATE</code>.</li>
<li>Deleting records using <code>DELETE</code>.</li>
</ul>
<h2>Technologies Used</h2>
<ul>
<li>MySQL</li>
<li>MySQL Workbench</li>
<li>SQL</li>
<li>Git</li>
<li>GitHub</li>
</ul>
<h2>1. Creating the Database</h2>
<p>The first step was to create a database to store NaijaMart's inventory information.</p>
<p>In MySQL, a database serves as a container for organizing related data, including tables and other database objects. I created a database named <code>naijamart_db</code> using the <code>CREATE DATABASE</code> statement.</p>
<pre><code class="language-sql">CREATE DATABASE naijamart_db;
</code></pre>
<p>After creating the database, I selected it using the <code>USE</code> statement so that subsequent SQL commands would execute within the correct database.</p>
<pre><code class="language-sql">USE naijamart_db;
</code></pre>
<p>To verify that the database was created successfully, I ran:</p>
<pre><code class="language-sql">SHOW DATABASES;
</code></pre>
<p>I also confirmed that the correct database was selected by executing:</p>
<pre><code class="language-sql">SELECT DATABASE();
</code></pre>
<p>This returned <code>naijamart_db</code>, confirming that I was working inside the correct database.</p>
<p>Creating and selecting the database established the foundation for the inventory management system. The next step was to design a table for storing the products sold by NaijaMart.</p>
<h2>2. Creating the Products Table</h2>
<p>After creating the database, the next step was to design a table for storing NaijaMart's inventory records.</p>
<p>I created a table named <code>products</code> to store information about each product, including its name, description, category, price, available stock, and creation timestamp.</p>
<pre><code class="language-sql">CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    description TEXT,
    category VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    quantity INT NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
</code></pre>
<h3>Understanding the Table Structure</h3>
<p>The table contains seven columns:</p>
<ul>
<li><code>id</code>: An integer that uniquely identifies each product. I used <code>AUTO_INCREMENT</code> so MySQL automatically generates an ID for each new record, while <code>PRIMARY KEY</code> ensures that each ID is unique.</li>
<li><code>name</code>: Stores the product name using <code>VARCHAR(100)</code>. I applied <code>NOT NULL</code> to require a name and <code>UNIQUE</code> to prevent duplicate product names.</li>
<li><code>description</code>: Uses the <code>TEXT</code> data type to store product descriptions.</li>
<li><code>category</code>: Stores the product category, such as Grains, Tubers, or Seafood. It is defined as <code>VARCHAR(100) NOT NULL</code>.</li>
<li><code>price</code>: Uses <code>DECIMAL(10,2)</code> to store prices with two decimal places. This is appropriate for monetary values because it provides exact decimal storage.</li>
<li><code>quantity</code>: Stores the available stock as an integer. The <code>DEFAULT 0</code> constraint ensures that a product receives a stock quantity of zero if one is not explicitly supplied.</li>
<li><code>created_at</code>: Uses <code>TIMESTAMP DEFAULT CURRENT_TIMESTAMP</code> to automatically record the date and time a product is added.</li>
</ul>
<h3>Verifying the Table</h3>
<p>After executing the <code>CREATE TABLE</code> statement, I verified that the table was created successfully using:</p>
<pre><code class="language-sql">SHOW TABLES;
</code></pre>
<p>To inspect the columns, data types, constraints, and defaults, I ran:</p>
<pre><code class="language-sql">DESCRIBE products;
</code></pre>
<p>This confirmed that the table was ready to store inventory records.</p>
<p>With the database and table structure in place, the next step was to populate the inventory with sample products.</p>
<h2>3. Inserting Products into the Database</h2>
<p>After creating the <code>products</code> table, I needed to populate it with sample inventory records to test the database operations.</p>
<p>I added 15 products representing common Nigerian foodstuffs and ingredients, including rice, beans, garri, yam, palm oil, groundnut oil, and other everyday cooking essentials.</p>
<p>To insert records into a MySQL table, I used the <code>INSERT INTO</code> statement.</p>
<pre><code class="language-sql">INSERT INTO products (name, description, category, price, quantity)
VALUES
('Ofada Rice 5kg', 'Locally grown Ofada rice, 5kg bag', 'Grains', 18500.00, 20),
('White Garri 5kg', 'White cassava granules, 5kg bag', 'Grains', 6500.00, 35),
('Honey Beans 5kg', 'Nigerian honey beans, 5kg bag', 'Grains', 12500.00, 18),
('Yellow Garri 5kg', 'Yellow cassava granules, 5kg bag', 'Grains', 7000.00, 25),
('Ijebu Garri 2kg', 'Fine-textured Ijebu garri, 2kg pack', 'Grains', 3500.00, 12),
('Yam Tuber', 'Fresh medium-sized yam tuber', 'Tubers', 4500.00, 30),
('Dried Crayfish 500g', 'Cleaned and ground dried crayfish, 500g', 'Seafood', 8500.00, 8),
('Stockfish 1kg', 'Dried stockfish pieces, 1kg pack', 'Seafood', 18000.00, 6),
('Palm Oil 5 Litres', 'Locally produced red palm oil, 5-litre container', 'Cooking Oil', 14500.00, 15),
('Groundnut Oil 5 Litres', 'Refined groundnut cooking oil, 5-litre container', 'Cooking Oil', 16500.00, 10),
('Egusi 1kg', 'Dried melon seeds, 1kg pack', 'Food Ingredients', 7500.00, 22),
('Ogbono 500g', 'Dried African bush mango seeds, 500g pack', 'Food Ingredients', 6000.00, 9),
('Dried Catfish 1kg', 'Smoked and dried catfish, 1kg pack', 'Seafood', 12000.00, 7),
('Semovita 2kg', 'Semolina flour, 2kg pack', 'Grains', 5200.00, 28),
('Dried Pepper 500g', 'Ground dried red pepper, 500g pack', 'Food Ingredients', 4000.00, 32);
</code></pre>
<h3>Understanding the INSERT Statement</h3>
<p>The <code>INSERT INTO</code> statement specifies the table into which the records will be inserted, followed by the columns that will receive the data.</p>
<p>In this case, I specified five columns:</p>
<ul>
<li><code>name</code></li>
<li><code>description</code></li>
<li><code>category</code></li>
<li><code>price</code></li>
<li><code>quantity</code></li>
</ul>
<p>The <code>VALUES</code> keyword specifies the data being inserted. Each set of parentheses represents a single product record, and the values follow the same order as the columns specified in the statement.</p>
<p>I did not include the <code>id</code> or <code>created_at</code> columns because MySQL automatically generates their values based on the <code>AUTO_INCREMENT</code> and <code>DEFAULT CURRENT_TIMESTAMP</code> definitions in the table.</p>
<h3>Verifying the Inserted Records</h3>
<p>After inserting the products, I retrieved all records from the table using:</p>
<pre><code class="language-sql">SELECT * FROM products;
</code></pre>
<p>This allowed me to confirm that the products had been inserted successfully and inspect the values stored in each column.</p>
<p>To verify the number of records in the table, I used the <code>COUNT()</code> aggregate function:</p>
<pre><code class="language-sql">SELECT COUNT(*) AS total_products
FROM products;
</code></pre>
<p>The query returned 15, confirming that the inventory contained the 15 products I had inserted.</p>
<p>With the inventory populated, I could now begin retrieving specific records and filtering products based on different conditions.</p>
<h2>4. Retrieving Products with SELECT</h2>
<p>After inserting the sample products, the next step was to retrieve information from the database.</p>
<p>In MySQL, the <code>SELECT</code> statement is used to retrieve records from a table.</p>
<h3>4.1 Retrieving All Products</h3>
<p>To display every column and record in the <code>products</code> table, I used:</p>
<pre><code class="language-sql">SELECT * FROM products;
</code></pre>
<p>The asterisk (<code>*</code>) tells MySQL to return all columns.</p>
<h3>4.2 Retrieving Specific Columns</h3>
<p>Sometimes, displaying every column is unnecessary. To retrieve only the product name, price, and available quantity:</p>
<pre><code class="language-sql">SELECT name, price, quantity
FROM products;
</code></pre>
<p>This makes the result easier to read when only specific information is needed.</p>
<h3>4.3 Filtering Products by Category</h3>
<p>The <code>WHERE</code> clause allows records to be filtered based on a condition.</p>
<p>For example, to retrieve products in the Grains category:</p>
<pre><code class="language-sql">SELECT *
FROM products
WHERE category = 'Grains';
</code></pre>
<h3>4.4 Finding Products Above a Specific Price</h3>
<p>To retrieve products priced above ₦10,000:</p>
<pre><code class="language-sql">SELECT *
FROM products
WHERE price &gt; 10000.00;
</code></pre>
<p>The <code>&gt;</code> operator selects records whose prices are greater than the specified amount.</p>
<h3>4.5 Identifying Products with Low Stock</h3>
<p>To identify products with fewer than 10 units remaining:</p>
<pre><code class="language-sql">SELECT *
FROM products
WHERE quantity &lt; 10;
</code></pre>
<p>This is useful for identifying products that may need to be restocked.</p>
<h3>What I learned</h3>
<p>Through these queries, I practised retrieving all records, selecting specific columns, and filtering data using the <code>WHERE</code> clause and comparison operators.</p>
<h2>5. Sorting and Limiting Inventory Results</h2>
<p>After learning how to retrieve and filter products, I moved on to sorting records and controlling the number of results returned.</p>
<p>MySQL provides <code>ORDER BY</code> for sorting records and <code>LIMIT</code> for restricting the number of rows returned.</p>
<h3>Sorting products by price (ascending)</h3>
<p>I used <code>ASC</code> to arrange products from the lowest price to the highest.</p>
<pre><code class="language-sql">SELECT *
FROM products
ORDER BY price ASC;
</code></pre>
<h3>Sorting products by price (descending)</h3>
<p>To display the most expensive products first, I used <code>DESC</code>.</p>
<pre><code class="language-sql">SELECT *
FROM products
ORDER BY price DESC;
</code></pre>
<h3>Sorting products alphabetically</h3>
<p>I also sorted the inventory by product name.</p>
<pre><code class="language-sql">SELECT *
FROM products
ORDER BY name ASC;
</code></pre>
<p>This arranged product names alphabetically from A to Z.</p>
<h3>Displaying the five most expensive products</h3>
<p>By combining <code>ORDER BY</code> with <code>LIMIT</code>, I retrieved only the five most expensive products.</p>
<pre><code class="language-sql">SELECT *
FROM products
ORDER BY price DESC
LIMIT 5;
</code></pre>
<h3>Displaying the five products with the lowest stock</h3>
<p>I used the following query to identify the five products with the smallest available quantities.</p>
<pre><code class="language-sql">SELECT *
FROM products
ORDER BY quantity ASC
LIMIT 5;
</code></pre>
<h3>What I learned</h3>
<p>This exercise helped me understand how to:</p>
<ul>
<li>Sort records using <code>ORDER BY</code>.</li>
<li>Arrange results in ascending (<code>ASC</code>) and descending (<code>DESC</code>) order.</li>
<li>Sort text values alphabetically.</li>
<li>Restrict query results using <code>LIMIT</code>.</li>
<li>Combine multiple SQL clauses to retrieve useful inventory information.</li>
</ul>
<h2>6. Updating Product Information with UPDATE</h2>
<p>An inventory database needs to support changes to existing product information. Prices may change, and stock quantities increase or decrease as products are received or sold.</p>
<p>MySQL provides the <code>UPDATE</code> statement to modify existing records.</p>
<h3>Updating a product's price</h3>
<p>I started by changing the price of Ofada Rice from ₦18,500 to ₦19,500.</p>
<pre><code class="language-sql">UPDATE products
SET price = 19500.00
WHERE name = 'Ofada Rice 5kg';
</code></pre>
<p>The <code>SET</code> clause specifies the new value, while <code>WHERE</code> identifies the record to update.</p>
<p>I verified the change with:</p>
<pre><code class="language-sql">SELECT name, price, quantity
FROM products
WHERE name = 'Ofada Rice 5kg';
</code></pre>
<h3>Updating stock quantity</h3>
<p>Next, I updated the available quantity of Ofada Rice from 20 to 40 units.</p>
<pre><code class="language-sql">UPDATE products
SET quantity = 40
WHERE name = 'Ofada Rice 5kg';
</code></pre>
<h3>Updating multiple columns</h3>
<p>MySQL also allows multiple columns to be updated in one statement.</p>
<p>I used this query to change the price and quantity of Honey Beans.</p>
<pre><code class="language-sql">UPDATE products
SET
    price = 13200.00,
    quantity = 25
WHERE name = 'Honey Beans 5kg';
</code></pre>
<h3>Verifying the updates</h3>
<p>To confirm both products were updated correctly, I used:</p>
<pre><code class="language-sql">SELECT name, price, quantity
FROM products
WHERE name IN (
    'Ofada Rice 5kg',
    'Honey Beans 5kg'
);
</code></pre>
<h3>What I learned</h3>
<ul>
<li>Updating existing records with <code>UPDATE</code>.</li>
<li>Assigning new values using <code>SET</code>.</li>
<li>Targeting specific records with <code>WHERE</code>.</li>
<li>Updating multiple columns in a single statement.</li>
<li>Verifying database changes with <code>SELECT</code>.</li>
</ul>
<p>One important lesson is that omitting the <code>WHERE</code> clause from an <code>UPDATE</code> statement can modify every record in the table.</p>
<h2>7. Deleting Products with DELETE</h2>
<p>The next operation was removing products from the inventory.</p>
<p>In MySQL, the <code>DELETE</code> statement removes existing records from a table.</p>
<h3>Identifying the product</h3>
<p>Before deleting a product, I first checked that it existed in the database.</p>
<pre><code class="language-sql">SELECT *
FROM products
WHERE name = 'Dried Pepper 500g';
</code></pre>
<h3>Deleting a product</h3>
<p>I used the following statement to remove Dried Pepper 500g from the inventory.</p>
<pre><code class="language-sql">DELETE FROM products
WHERE name = 'Dried Pepper 500g';
</code></pre>
<p>The <code>WHERE</code> clause ensures that only the record matching the specified product name is deleted.</p>
<h3>Verifying the deletion</h3>
<p>After executing the DELETE statement, I ran another SELECT query to confirm that the product had been removed.</p>
<pre><code class="language-sql">SELECT *
FROM products
WHERE name = 'Dried Pepper 500g';
</code></pre>
<p>The query returned an empty result set, confirming that the product was no longer in the table.</p>
<p>I also checked the remaining number of products:</p>
<pre><code class="language-sql">SELECT COUNT(*) AS total_products
FROM products;
</code></pre>
<p>The result was 14 products, down from the original 15.</p>
<h3>What I learned</h3>
<ul>
<li>Removing records using <code>DELETE</code>.</li>
<li>Targeting specific records with <code>WHERE</code>.</li>
<li>Verifying deleted records using <code>SELECT</code>.</li>
<li>Counting remaining records using <code>COUNT(*)</code>.</li>
</ul>
<p>An important lesson is that executing <code>DELETE</code> without a <code>WHERE</code> clause can remove all records from a table. Therefore, checking the condition before deletion is essential.</p>
<h2>Note</h2>
<p>The SQL script is organised into sections covering different database operations. For the first run, execute the statements in order, starting with database creation and ending with product deletion.</p>
<p>If you need to execute the setup statements again, use <code>IF NOT EXISTS</code> to avoid errors when the database or table already exists.</p>
<p><strong>Database creation:</strong></p>
<pre><code class="language-sql">CREATE DATABASE IF NOT EXISTS naijamart_db;
</code></pre>
<p><strong>Table creation:</strong></p>
<pre><code class="language-sql">CREATE TABLE IF NOT EXISTS products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    description TEXT,
    category VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    quantity INT NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
</code></pre>
<p>These clauses prevent errors caused by creating an existing database or table. However, they do not prevent duplicate product records when the <code>INSERT</code> statement is executed again.</p>
<p>To avoid duplicate-key errors, check whether the products already exist before inserting them. Also, be careful when rerunning <code>UPDATE</code> and <code>DELETE</code> statements, as they modify or remove existing records.</p>
<p><strong>Alternatively, to start with a completely fresh database</strong>, you can run:</p>
<pre><code class="language-sql">DROP DATABASE IF EXISTS naijamart_db;
CREATE DATABASE naijamart_db;
USE naijamart_db;
</code></pre>
<p><strong>Warning:</strong> <code>DROP DATABASE</code> permanently deletes the database and all its tables and records. Only use it when you are comfortable losing the existing data and starting over.</p>
<h2>Conclusion</h2>
<p>Building NaijaMart's inventory database taught me that SQL is easy to start and easy to get wrong. Three habits stood out. First, I ran a <code>SELECT</code> right after every <code>INSERT</code>, <code>UPDATE</code> and <code>DELETE</code>, so I never assumed a change had done what I intended. Second, I treated <code>WHERE</code> as a safety device, because leaving it out of an <code>UPDATE</code> or <code>DELETE</code> affects every row. Third, I stored prices as <code>DECIMAL(10,2)</code> instead of a floating-point type, because money needs exact values.</p>
<p>The database is small, one table with 15 products, but it already answers real questions: what is running low, what costs the most, and what changed.</p>
<p>Next, I want to add a second table, such as suppliers or orders, and connect it to products with a foreign key and <code>JOIN</code> queries. I also want to add an index on <code>category</code> and see how it affects query speed.</p>
<p>The full script and screenshots are on GitHub: <a href="https://github.com/biyiemmy/naijamart-inventory-management">https://github.com/biyiemmy/naijamart-inventory-management</a></p>
]]></content:encoded></item><item><title><![CDATA[How I Write Git Commit Messages: My Personal Convention]]></title><description><![CDATA[How I write clear Git commit messages using a type(scope) format, with real examples for features, bug fixes, chores and docs.]]></description><link>https://biyiemmy.hashnode.dev/how-i-write-git-commit-messages-my-personal-convention</link><guid isPermaLink="true">https://biyiemmy.hashnode.dev/how-i-write-git-commit-messages-my-personal-convention</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[version control]]></category><category><![CDATA[software development]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Emmanuel Adebiyi]]></dc:creator><pubDate>Tue, 01 Dec 2026 02:18:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/60af59d3-9639-4af3-9e84-2e1374079c7b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>When I work on a project, most of my attention goes to the code: building features, fixing bugs, testing endpoints. But how I record those changes in Git matters just as much, and it is the part I used to neglect.</p>
<p>It is tempting to commit with <code>update</code>, <code>changes</code>, or <code>fixed stuff</code> just to move on. Those messages make sense at the time, then become useless when I revisit a project weeks later. So I settled on a small convention that is consistent, simple, and descriptive enough that I can follow my own history without opening every commit.</p>
<h2>Why I Care About Commit Messages</h2>
<p>Git records what changed. The commit message records why. When I scan a project's history, I want to see at a glance whether I added a feature, fixed a bug, updated dependencies, or touched the docs.</p>
<p>Compare these:</p>
<p><strong>Before</strong></p>
<pre><code class="language-text">update files
changes
done
</code></pre>
<p><strong>After</strong></p>
<pre><code class="language-text">ft(orders): add order creation endpoint
fix(orders): allow order status updates
ch(dependencies): add project requirements
docs(readme): add project documentation
</code></pre>
<p>The difference is that the second set tells me what happened before I even open the commit.</p>
<p>For me, a good commit message isn't just a description of the files I changed. It should communicate the purpose of the change.</p>
<h2>The Format I Use</h2>
<p>I use the following structure which is inspired by <a href="https://www.conventionalcommits.org/">Conventional Commits</a>:</p>
<pre><code class="language-text">type(scope): description
</code></pre>
<p>Each part serves a purpose:</p>
<ul>
<li><strong>Type:</strong> Identifies the kind of change I made.</li>
<li><strong>Scope:</strong> Identifies the area of the project affected.</li>
<li><strong>Description:</strong> Briefly explains what I changed.</li>
</ul>
<p>For example:</p>
<pre><code class="language-bash">ft(orders): add order creation endpoint
</code></pre>
<p>Here, <code>ft</code> tells me that I added a feature, <code>orders</code> identifies the area of the application I worked on, and the description explains the actual change.</p>
<p>I keep the description short, write it in lowercase, and use the imperative mood. In other words, I write <code>add order creation endpoint</code> rather than <code>added order creation endpoint</code>. It keeps the message direct and consistent.</p>
<p>I also try to keep the first line around 50 characters, ideally within 50 to 72 characters, so it remains readable in the terminal and Git history.</p>
<h2>My Commit Types</h2>
<p>I don't use every possible commit type. I stick to the ones I find useful in my day-to-day workflow.</p>
<table>
<thead>
<tr>
<th>Prefix</th>
<th>Meaning</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td><code>ft</code></td>
<td>Feature</td>
<td><code>ft(meals): add meal creation endpoint</code></td>
</tr>
<tr>
<td><code>fix</code></td>
<td>Bug fix</td>
<td><code>fix(orders): allow order status updates</code></td>
</tr>
<tr>
<td><code>ch</code></td>
<td>Chore</td>
<td><code>ch(dependencies): add project requirements</code></td>
</tr>
<tr>
<td><code>docs</code></td>
<td>Documentation</td>
<td><code>docs(readme): add project documentation</code></td>
</tr>
</tbody></table>
<h3><code>ft</code> for features</h3>
<p>I use <code>ft</code> when I introduce new functionality to a project, such as adding an endpoint, implementing a search feature, or introducing a new capability.</p>
<pre><code class="language-bash">ft(meals): add meal creation endpoint
</code></pre>
<h3><code>fix</code> for bug fixes</h3>
<p>I use <code>fix</code> when correcting something that isn't working as expected or when changing existing behaviour to resolve a problem.</p>
<pre><code class="language-bash">fix(orders): allow order status updates
</code></pre>
<h3><code>ch</code> for chores</h3>
<p>I use <code>ch</code> for maintenance tasks that don't introduce application features or directly fix bugs. This could include adding dependencies, updating configuration, or general project maintenance.</p>
<pre><code class="language-bash">ch(dependencies): add project requirements
</code></pre>
<h3><code>docs</code> for documentation</h3>
<p>I use <code>docs</code> when updating documentation, writing setup instructions, documenting endpoints, or improving a project's README.</p>
<pre><code class="language-bash">docs(readme): add project documentation
</code></pre>
<h2>Why I Use Shortened Prefixes</h2>
<p>My convention is inspired by Conventional Commits, but it isn't an exact implementation of the specification.</p>
<p>Conventional Commits uses prefixes such as <code>feat</code> for features and <code>chore</code> for maintenance. I shortened these to <code>ft</code> and <code>ch</code> because I prefer a compact format.</p>
<p>It's a personal preference, not a technical improvement. The shorter prefixes are easy for me to recognise and use, but they may be less obvious to someone unfamiliar with my commit history. They may also require additional configuration when working with tools that expect standard Conventional Commit types, such as <code>commitlint</code> or release automation.</p>
<p>If a project requires compatibility with those tools, I'd use the standard prefixes instead:</p>
<pre><code class="language-text">feat(orders): add order creation endpoint
chore(dependencies): add project requirements
</code></pre>
<p>For my personal projects, however, I prefer sticking with my shortened convention.</p>
<h2>Why I Include a Scope</h2>
<p>The scope is the part inside the parentheses. It identifies the area of the project affected by the commit.</p>
<p>For example:</p>
<pre><code class="language-bash">ft(meals): add meal creation endpoint
ft(orders): add order creation endpoint
fix(orders): allow order status updates
</code></pre>
<p>The scope makes it easier to scan my commit history and understand which part of the application a change belongs to without opening the commit.</p>
<p>I don't force a scope into every message. When a change affects the entire project or doesn't belong to a specific module, I leave it out.</p>
<pre><code class="language-bash">ch: update project configuration
</code></pre>
<p>The goal is to add context when it is useful, not to make every message unnecessarily complicated.</p>
<h2>What About Refactoring, Tests, and Formatting?</h2>
<p>Not every change fits neatly into the types I use regularly.</p>
<p>If I refactor existing code without changing functionality, I can use <code>refactor</code>. If I'm adding or updating tests, I can use <code>test</code>. For formatting or other maintenance work, I can use <code>ch</code>.</p>
<p>For example:</p>
<pre><code class="language-bash">refactor(orders): simplify order validation
test(meals): add meal creation tests
ch(formatting): organize imports
</code></pre>
<p>I don't need to introduce a new prefix for every possible type of change. I just need the type to communicate what I did clearly.</p>
<h2>My Rules for Writing Commit Messages</h2>
<ol>
<li><strong>Keep it lowercase:</strong> I prefer lowercase commit messages for consistency.</li>
<li><strong>Keep it concise:</strong> Describe the change without turning the commit message into a paragraph.</li>
<li><strong>Use a scope where appropriate:</strong> Identify the area affected when it adds useful context.</li>
<li><strong>Use the imperative mood:</strong> Write <code>add</code>, <code>fix</code>, or <code>update</code>, not <code>added</code>, <code>fixed</code>, or <code>updated</code>.</li>
<li><strong>Be specific:</strong> Avoid vague messages like <code>update code</code>, <code>make changes</code>, or <code>final work</code>.</li>
<li><strong>Keep commits focused:</strong> Commit related changes together instead of mixing unrelated tasks.</li>
<li><strong>Aim for a short first line:</strong> Keep it readable when viewing Git history.</li>
</ol>
<p>These aren't strict rules enforced by Git. They are conventions I choose to follow to make my workflow more consistent.</p>
<h2>Putting It Into Practice</h2>
<p>Writing commit messages this way doesn't require any additional tools or complicated Git configuration. It's simply a habit I apply whenever I'm ready to commit a change.</p>
<p>For example, after adding a new endpoint to my FastAPI project:</p>
<pre><code class="language-bash">git add main.py
git commit -m "ft(meals): add meal creation endpoint"
git push origin main
</code></pre>
<p>When updating documentation:</p>
<pre><code class="language-bash">git add README.md
git commit -m "docs(readme): add project documentation"
git push origin main
</code></pre>
<p>And when fixing an issue with an existing endpoint:</p>
<pre><code class="language-bash">git add main.py
git commit -m "fix(orders): allow order status updates"
git push origin main
</code></pre>
<p>The commands are the same as ever. Only the message changed.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6132e57a36015b2f4e1292b5/e6ff2c11-b2b5-4865-8582-44912e9f4608.png" alt="" style="display:block;margin:0 auto" />

<h2>Conclusion</h2>
<p>Commit messages don't need to be complicated, only meaningful and consistent. This convention made me stop and ask what I did, where, and why before every commit. When I return to a project or review changes, I can read the history like a short changelog instead of decoding it.</p>
]]></content:encoded></item></channel></rss>