Skip to content

categories.py

This file defines API endpoints for managing product categories, enabling creation, retrieval, and deletion operations. It integrates authentication and database services to ensure secure and persistent category data management.

Scope

  • Manages the creation of new product categories.

  • Retrieves specific category details by identifier.

  • Provides a paginated list of all available categories.

  • Handles the secure deletion of existing categories.

  • Authenticates and authorizes user access to category operations.

File diagram - "categories.py" /app/routes/categories.pyFile diagram - "categories.py"  GlobalImportsAPIRouterDependsstatusHTTPExceptionQuerySessionget_dbget_tokenCategoryCreateCategoryResponseCategoryServiceUserServicelogger/app/routes/categories.pyrouterget_current_user()create_category()list_categories()APIRouter()router.post()router.get()router.delete()get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()create_categorydb_categoryDepends()CategoryService.create_category()CategoryResponse.from_orm()logger.error()str()HTTPException()list_categoriescategoriesQuery()Depends()CategoryService.get_all_categories()CategoryResponse.from_orm()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
File diagram - "categories.py" /app/routes/categories.pyFile diagram - "categories.py"  GlobalImportsAPIRouterDependsstatusHTTPExceptionQuerySessionget_dbget_tokenCategoryCreateCategoryResponseCategoryServiceUserServicelogger/app/routes/categories.pyrouterget_current_user()create_category()list_categories()APIRouter()router.post()router.get()router.delete()get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()create_categorydb_categoryDepends()CategoryService.create_category()CategoryResponse.from_orm()logger.error()str()HTTPException()list_categoriescategoriesQuery()Depends()CategoryService.get_all_categories()CategoryResponse.from_orm()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Imports

  • APIRouter from fastapi

    Defines API routes and handles HTTP requests, structuring the application's external interface for category management operations.

  • Depends from fastapi

    Manages dependency injection for database sessions, authentication tokens, and current user context across API endpoints.

  • status from fastapi

    Provides HTTP status codes for responses, ensuring clear communication of operation outcomes and API consistency.

  • HTTPException from fastapi

    Raises standard HTTP errors for invalid requests or missing resources, maintaining API consistency and client-side error handling.

  • Query from fastapi

    Extracts and validates query parameters from incoming requests, enforcing data integrity and pagination rules for category listings.

  • Session from sqlalchemy.orm

    Manages database interactions and transactions, providing an ORM interface for data persistence and retrieval of categories.

  • get_db from app.core.database

    Provides a database session dependency, abstracting database connection management for routes and ensuring consistent data access.

  • get_token from app.core.security

    Extracts and validates authentication tokens from request headers, securing API access and identifying the requesting user.

  • CategoryCreate from app.schemas.schemas

    Defines the data structure for creating new categories, ensuring input validation and consistency for incoming request bodies.

  • CategoryResponse from app.schemas.schemas

    Defines the data structure for category responses, standardizing output format for clients and ensuring consistent data representation.

  • CategoryService from app.services.service

    Encapsulates business logic for category operations, abstracting data access and domain rules from the API layer for reusability.

  • UserService from app.services.service

    Provides methods for retrieving user information, supporting authentication and authorization processes within the category API.

  • logger from app.core.logging

    Logs application events and errors, aiding in debugging, monitoring, and operational insights for category management operations.

Variables

  • router

    An instance of APIRouter that groups related API endpoints for categories, defining their base path and descriptive tags for documentation.

Global Code

This line initializes the FastAPI router for category-related API endpoints, setting the base URL prefix and assigning a descriptive tag for documentation.

Routers

router

This `router` defines API endpoints for managing product `Categories` within the application. It provides a structured, versioned approach for category-related operations, ensuring consistent routing and clear organization. Integrating seamlessly into the main FastAPI application, it groups all category-related routes under the `/api/v1/categories` `prefix`.

Prefix

/api/v1/categories

Configuration Details

Tags

  • Categories

Functions

get_current_user

public

Retrieves the currently authenticated user based on a provided token payload and database session. This function is crucial for securing endpoints, ensuring only valid, existing users can access protected resources throughout the application's authenticated sections.
=== " "

Activity Diagram - "get_current_user" /app/routes/categories.pyActivity Diagram - "get_current_user"  Inputs: token_payload, dbExtract user ID from token payloadRetrieve user from database by IDuser not found?yesnoRaise HTTP 404 exception (User not found)return User object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "get_current_user" /app/routes/categories.pyActivity Diagram - "get_current_user"  Inputs: token_payload, dbExtract user ID from token payloadRetrieve user from database by IDuser not found?yesnoRaise HTTP 404 exception (User not found)return User object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "get_current_user" /app/routes/categories.pyMethod diagram - "get_current_user"  get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "get_current_user" /app/routes/categories.pyMethod diagram - "get_current_user"  get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "get_current_user" Sequence Diagram - "get_current_user"  get_current_userget_tokenget_dbUserServiceCallerget_current_userget_tokenget_dbUserServiceHTTPExceptionCallerCallerget_current_userget_current_userget_tokenget_tokenget_dbget_dbUserServiceUserServiceHTTPExceptionHTTPExceptionget_current_userget_tokenget_dbUserServiceFunction Entryget_current_user(token_payload, db)Retrieve Token Payloadget_token()token_payloadRetrieve Database Sessionget_db()db_sessionExtract User IDExtract user_id from token_payloaduser_id = int(token_payload.get("sub"))Fetch User from Databaseget_user_by_id(db_session, user_id)user_objectHandle User Not Found or Return Useralt[user_object is None]HTTPException(status_code=404, detail="User not found")Function terminates by raising exceptionraise HTTPException[user_object is not None]user_object/app/routes/categories.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "get_current_user" Sequence Diagram - "get_current_user"  get_current_userget_tokenget_dbUserServiceCallerget_current_userget_tokenget_dbUserServiceHTTPExceptionCallerCallerget_current_userget_current_userget_tokenget_tokenget_dbget_dbUserServiceUserServiceHTTPExceptionHTTPExceptionget_current_userget_tokenget_dbUserServiceFunction Entryget_current_user(token_payload, db)Retrieve Token Payloadget_token()token_payloadRetrieve Database Sessionget_db()db_sessionExtract User IDExtract user_id from token_payloaduser_id = int(token_payload.get("sub"))Fetch User from Databaseget_user_by_id(db_session, user_id)user_objectHandle User Not Found or Return Useralt[user_object is None]HTTPException(status_code=404, detail="User not found")Function terminates by raising exceptionraise HTTPException[user_object is not None]user_object/app/routes/categories.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def get_current_user(token_payload: dict = Depends(get_token), db: Session = Depends(get_db)):

Input Parameters

  • token_payload (dict)

    Contains decoded authentication token information, typically including the user's identifier. This dictionary is essential for extracting the user_id to locate the correct user record within the system's database.

  • db (Session)

    Represents the active database session, providing the necessary connection to query user data. This session is vital for interacting with the database to retrieve the user object corresponding to the extracted user_id.

Output / Return Values

  • user (User)

    The User object representing the authenticated user found in the database. This object contains all relevant user details, enabling subsequent operations and authorization checks for protected application resources.

Exceptions

  • HTTPException 404 Not Found [404]

    Raised when no user is found in the database corresponding to the user_id extracted from the token_payload. This indicates an invalid or non-existent user attempting to access resources.

Logic / Execution Flow

  • Extract the user_id by converting the sub key from the token_payload dictionary to an integer.
  • Call UserService.get_user_by_id with the database session db and the extracted user_id to retrieve the user object.
  • Check if the user object returned from UserService.get_user_by_id is None (i.e., no user was found).
  • If user is None:
    • Raise an HTTPException with a status_code of 404 and a detail message of "User not found".
  • If a user object is successfully retrieved:
    • Return the user object.

Usage Tips

  • Integrate get_current_user as a FastAPI dependency in protected endpoint functions. This ensures automatic user authentication and injection, simplifying access control logic and maintaining consistent security across your API.

  • Ensure the get_token dependency correctly handles token validation and expiration before get_current_user is called. This prevents unnecessary database lookups for invalid tokens, improving efficiency and overall system responsiveness.

Additional Notes

  • The user_id extraction assumes token_payload contains a sub key, which is standard for JWT subject claims. Mismatched token structures could lead to KeyError or ValueError if not properly handled upstream.

  • This function relies on UserService.get_user_by_id for database interaction. Performance of user retrieval directly impacts endpoint latency, so ensure UserService is optimized for fast lookups by user_id.

FAQs

Why are CategoryService and UserService used instead of direct database operations within the routes?

This design separates concerns, keeping business logic out of the API layer. Services encapsulate domain operations, promoting reusability, testability, and maintainability, while routes focus solely on request handling and response formatting.

What is the purpose of get_current_user and get_token dependencies in the API endpoints?

These dependencies ensure that all protected API endpoints require a valid authenticated user. get_token extracts and validates the JWT, while get_current_user fetches the corresponding user object for authorization.

Why are HTTPException instances raised instead of returning standard Python exceptions?

HTTPException from FastAPI automatically translates into appropriate HTTP responses with specific status codes and detail messages. This standardizes error reporting for API clients, making error handling predictable and consistent.

How are input data validation and output data serialization handled for category operations?

Pydantic models like CategoryCreate and CategoryResponse are used. CategoryCreate validates incoming request bodies, while CategoryResponse ensures consistent serialization of data returned from the API.

Insights

Metric Score Level
Complexity 0.85 Very Complex
Security 0.80 Secure
Performance 0.50 Needs Improvement

Complexity

Medium - Duplicate Error Handling Logic

The try-except blocks for create_category and delete_category are duplicated. Abstracting this into a common error handler or decorator would improve maintainability.

Security

High - Insufficient Authorization for Category Operations

While current_user.id is passed to services, explicit authorization checks (e.g., ownership, admin role) are not visible at the API layer for delete_category or create_category.

Performance

Medium - Missing Caching for Category Retrieval

Frequently accessed categories are not cached, potentially leading to repeated database queries for static data. Implementing a caching layer could significantly improve read performance.