Skip to content

Sachinsachin21/FastAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI


README.md

You can copy and paste the following content into a new file named README.md in your project's root directory.

# FastAPI Product CRUD API

This project is a simple yet complete RESTful API for managing a product inventory. It is built using Python with the **FastAPI** framework and uses **SQLAlchemy** for ORM to interact with a **PostgreSQL** database. The API provides full CRUD (Create, Read, Update, Delete) functionality for products.

## Features

-   **Create, Read, Update, Delete (CRUD)** operations for products.
-   **Pydantic Models** for robust data validation and serialization.
-   **SQLAlchemy ORM** for database interaction and management.
-   **Dependency Injection** for managing database sessions.
-   **Automatic Database Initialization**: The application automatically creates the necessary database tables on startup.
-   **Initial Data Seeding**: Populates the database with sample products on the first run if the database is empty.
-   **CORS Middleware**: Pre-configured to allow requests from a frontend application (e.g., React on `http://localhost:3000`).

## Tech Stack

-   **Backend**: Python 3
-   **Framework**: FastAPI
-   **Database**: PostgreSQL
-   **ORM**: SQLAlchemy
-   **Data Validation**: Pydantic
-   **ASGI Server**: Uvicorn

---

## Project Structure Explained

The project is organized into logical modules to separate concerns:

. ├── db.py # Database connection and session management ├── db_model.py # SQLAlchemy ORM models (database table structure) ├── main.py # Main FastAPI application, API endpoints, and business logic ├── model.py # Pydantic models for data validation (request/response shapes) └── requirements.txt # Project dependencies


-   **`main.py`**: This is the entry point of the application. It creates the FastAPI app instance, defines all the API endpoints (`/products/`), handles the business logic for each endpoint, and includes the database initialization logic.
-   **`db.py`**: This file is responsible for setting up the connection to the PostgreSQL database. It creates the SQLAlchemy engine and the `SessionLocal` factory, which is used to create new database sessions for each request.
-   **`model.py`**: Defines the Pydantic `product` model. This model is used by FastAPI to validate incoming request data (e.g., when creating or updating a product) and to serialize data for outgoing responses. It defines the *shape* of the data your API expects and returns.
-   **`db_model.py`**: Defines the SQLAlchemy `product` model. This model maps the Python class to the `products` table in your PostgreSQL database. SQLAlchemy uses this model to execute SQL queries (CREATE, SELECT, UPDATE, DELETE) on your behalf.

---

## Getting Started

Follow these instructions to get the project up and running on your local machine.

### 1. Prerequisites

-   Python 3.8+
-   A running PostgreSQL database instance.

### 2. Installation & Setup

**1. Clone the repository:**
```bash
git clone <your-repository-url>
cd <your-repository-name>

2. Create and activate a virtual environment:

# For macOS/Linux
python3 -m venv venv
source venv/bin/activate

# For Windows
python -m venv venv
.\venv\Scripts\activate

3. Create a requirements.txt file with the following content:

fastapi
uvicorn[standard]
sqlalchemy
pydantic
psycopg2-binary

4. Install the dependencies:

pip install -r requirements.txt

5. Configure the Database:

  • Ensure your PostgreSQL server is running.
  • Create a database (e.g., Zachzzz).
  • Open the db.py file and update the db_url with your PostgreSQL connection string:
    # Example: postgresql://<user>:<password>@<host>:<port>/<database_name>
    db_url = "postgresql://postgres:3115Zach@localhost:5432/Zachzzz"

3. Running the Application

Once the setup is complete, run the application using Uvicorn:

uvicorn main:app --reload
  • main: Refers to the main.py file.
  • app: Refers to the app = FastAPI() object created inside main.py.
  • --reload: Automatically restarts the server whenever you make changes to the code.

The API will be available at http://127.0.0.1:8000.

You can access the interactive API documentation (provided by Swagger UI) at http://127.0.0.1:8000/docs.


API Endpoints

Here is a summary of the available API endpoints:

Method Endpoint Description Request Body (JSON) Success Response (200 OK)
GET /products/ Get a list of all products. None An array of product objects.
GET /products/{product_id} Get a single product by its ID. None The product object. Returns a 404 error if not found.
POST /products/ Create a new product. {"id": 0, "name": "string", ...} A success message with the created product data.
PUT /products/{product_id} Update an existing product. {"id": 0, "name": "string", ...} A success message with the updated product object.
DELETE /products/{product_id} Delete a product by its ID. None A success message.

Example Request Body for POST / PUT:

{
  "id": 0,
  "name": "New Gaming Mouse",
  "price": 75.50,
  "quantity": 25,
  "description": "A high-precision gaming mouse with RGB lighting."
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages