Build a CRUD API with FastAPI: India Step-By-Step

Learn to build a fast, modern CRUD API with Python's FastAPI. This step-by-step guide for Indian students includes database integration & deployment tips to boost your backend development skills for placements.

LB
UnboxCareer Team
Editorial ยท Free courses curator
February 9, 20265 min read
Build a CRUD API with FastAPI: India Step-By-Step

Building a working API is no longer a skill reserved for senior developers at big tech firms. In India's booming tech ecosystem, from startups like Razorpay and Swiggy to IT giants like TCS and Infosys, the ability to create robust back-end services is a fundamental requirement. FastAPI, a modern Python framework, has become a go-to choice for its speed and simplicity, making it perfect for students and job-seekers to learn and build impressive projects. This step-by-step guide will walk you through creating a fully functional CRUD (Create, Read, Update, Delete) API, the backbone of most applications, using tools and practices relevant to the Indian job market.

Why FastAPI is a Smart Choice for Indian Developers

FastAPI isn't just another framework; it's a career accelerator. Built on standard Python type hints, it offers incredible development speed and automatic, interactive API documentation. For Indian students preparing for placements, a FastAPI project on your resume demonstrates knowledge of modern, high-performance toolsโ€”a clear differentiator. Companies like Freshworks and Zomato value developers who can build efficient microservices quickly.

Compared to older frameworks like Flask or Django, FastAPI is asynchronous by design, meaning it can handle many more requests with the same resources. This efficiency is crucial for cost-sensitive Indian startups. Furthermore, its automatic generation of OpenAPI documentation (Swagger UI) is a massive time-saver, allowing you to focus on logic rather than writing manual docsโ€”a common pain point in Indian IT projects.

Setting Up Your Development Environment

Before writing code, you need a proper workspace. We'll use tools that are free and widely used in the industry.

  1. Install Python: Ensure you have Python 3.7 or above. You can download it from the official website. Verify by opening a terminal (Command Prompt or PowerShell) and typing python --version.
  2. Create a Virtual Environment: This keeps project dependencies isolated. In your project folder, run:
    python -m venv venv
    
    Activate it:
    • Windows: venv\Scripts\activate
    • macOS/Linux: source venv/bin/activate
  3. Install FastAPI and Uvicorn: With your virtual environment active, install the core packages:
    pip install fastapi uvicorn
    
    Uvicorn is the ASGI server that will run your FastAPI application.

This setup mirrors professional development practices and is the first step toward building production-ready code.

Building the Core CRUD API: A Task Manager Example

Let's build a simple Task Manager API. This is a classic project that covers all CRUD operations and is easily expandable. We'll model a task with an ID, title, description, and completion status.

First, create a file named main.py. This will be our application's entry point.

1. Creating the Basic App and Data Model

We start by importing FastAPI and defining a Pydantic model. Pydantic, included with FastAPI, uses Python type hints for data validationโ€”a huge advantage.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional

app = FastAPI(title="Task Manager API")

# In-memory "database" (a simple list for this example)
tasks_db = []

# Pydantic Model for Task
class Task(BaseModel):
    title: str
    description: Optional[str] = None
    completed: bool = False

2. Implementing the CREATE Operation (POST)

This endpoint will allow us to add new tasks. FastAPI makes it intuitive.

@app.post("/tasks/", response_model=Task)
def create_task(task: Task):
    # Simulate generating an ID
    task_dict = task.dict()
    task_dict["id"] = len(tasks_db) + 1
    tasks_db.append(task_dict)
    return task_dict

Test it by running uvicorn main:app --reload and visiting http://127.0.0.1:8000/docs. You'll see the interactive Swagger UI where you can try the POST endpoint.

3. Implementing the READ Operations (GET)

We need two GET endpoints: one to fetch all tasks and another to fetch a single task by its ID.

@app.get("/tasks/", response_model=list[Task])
def read_all_tasks():
    return tasks_db

@app.get("/tasks/{task_id}", response_model=Task)
def read_task(task_id: int):
    if task_id < 1 or task_id > len(tasks_db):
        raise HTTPException(status_code=404, detail="Task not found")
    return tasks_db[task_id - 1]  # Adjusting for zero-based index

4. Implementing the UPDATE Operation (PUT)

To update an existing task, we use the PUT method. This replaces the entire task resource.

@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
    if task_id < 1 or task_id > len(tasks_db):
        raise HTTPException(status_code=404, detail="Task not found")

    task_dict = updated_task.dict()
    task_dict["id"] = task_id
    tasks_db[task_id - 1] = task_dict
    return task_dict

5. Implementing the DELETE Operation (DELETE)

Finally, the endpoint to remove a task.

@app.delete("/tasks/{task_id}")
def delete_task(task_id: int):
    if task_id < 1 or task_id > len(tasks_db):
        raise HTTPException(status_code=404, detail="Task not found")

    deleted_task = tasks_db.pop(task_id - 1)
    return {"message": "Task deleted successfully", "deleted_task": deleted_task}

Congratulations! You now have a fully functional CRUD API. You can test all endpoints via the /docs page.

Connecting to a Real Database (SQLite)

While an in-memory list works for learning, real applications need a persistent database. Let's integrate SQLite, a lightweight database perfect for learning and small projects, using the sqlite3 module built into Python.

  • Create a Database Connection: Modify main.py to connect to a SQLite file.
  • Define a Table: Write SQL to create a tasks table.
  • Refactor CRUD Functions: Update each function to execute SQL commands (INSERT, SELECT, UPDATE, DELETE) instead of manipulating a list.

This step is crucial for your resume. Mentioning "Built a FastAPI CRUD API with SQLite database integration" shows practical, end-to-end backend development skills that recruiters at companies like Infosys and HCL actively look for in freshers.

Next Steps: From Project to Placement

You've built the core API. To turn this into a standout project for your portfolio and interviews, consider these enhancements. First, add user authentication using JWT (JSON Web Tokens) to secure your endpointsโ€”a common requirement in real-world apps. Next, containerize your application with Docker; this is a highly valued skill, with many Indian tech roles now requiring basic DevOps knowledge. Finally, deploy your API for free on platforms like Render or Railway to create a live link for your resume.

To deepen your backend and API expertise, explore free, high-quality courses tailored for the Indian learner. You can browse all free computer science courses to find structured paths. Specifically, consider mastering Python fundamentals through platforms like freeCodeCamp or NPTEL, and dive deeper into system design with resources from creators like Gaurav Sen (Gate Smashers). For a comprehensive learning path, check out our guide on how to become a backend developer in India, which covers the exact skills, projects, and salary expectations (often ranging from โ‚น4-10 LPA for freshers) in the current market.

Keep learning on UnboxCareer

Explore free courses, certificates, and career roadmaps curated for Indian students.