LogoLogo
CommunityBlogLicense
latest
latest
  • Overview
  • Social Registry
    • Features
      • Individuals and Households
        • 📔User Guides
          • 📔Create an Individual Registrant
          • 📔Create a Group and Add Individual Registrants to the Group
          • 📔Import CSV file to Social Registry
      • Offline Capabilities
        • ODK Importer
          • 📔User Guide
            • 📔Configure and Import ODK Form
            • 📔Import Specific ODK Forms using ODK Instance ID
        • Enumerator ID
      • Online Self Registration
      • Online Assisted Registration
        • 📔User Guides
          • 📔Create a New Household
          • 📔Create a New Individual in Registration Portal
          • 📔Create a New Portal User
          • 📔Configure Portal User to Limit Accessing Location
      • Deduplication
        • 📔User Guides
          • 📔Configure ID Deduplication, Deduplicate, and Save Duplicate Groups/Individuals
        • Deduplicator Service
      • Locking of Records
      • Dynamic Registry
      • Document Storage
      • Configurability
        • 📔User Guide
          • 📔Configure ID Types
          • 📔Configure Registrant Tags
          • 📔Configure Gender Types
          • 📔Configure Relationships
          • 📔Configure Group Types
          • 📔Configure Group Membership Kind
      • Role Based Access Control
        • 📔User Guide
          • 📔Create User
          • 📔Assign a Role to a User
      • Geo Targeting
      • Data Sharing
      • Multi-language Support
        • 📔User Guides
          • 📔Set Language Preference
      • Privacy and Security
      • Interoperability
      • Real-time Reporting
      • Monitoring and Reporting
      • ID Integration
        • ID Validation and Tokenisation
        • ID Authentication
          • 📔User Guides
            • 📔Configure eSignet Auth Provider for ID Authentication
            • 📔ID Authentication Process
            • 📔eSignet Client Creation
        • eSignet Integration
        • Fayda ID Integration
      • Verifiable Credentials Issuance
        • 📔User Guides
          • 📔Configure Inji to download Social Registry VCs
      • Automatic Computation of PMT
      • Record Revision History
      • SPAR Integration for Account Info
      • Unique Social ID
      • Audit Logs
      • Rapid Deployment Framework
      • Performance & Scale
      • Draft and Publish
      • Claim and Attest
    • Versions
    • Deployment
      • Domain names and Certificates
      • Install Odoo Modules
      • Packaging
        • 📘Docker Packaging Guide
        • 📘Helm Packaging Guide
    • Developer Zone
      • Technology Stack
      • API Reference
        • Search APIs
        • Individual APIs
        • Group APIs
      • Repositories
      • Background Tasks
      • Developer Install
        • 📘Developer Install of OpenG2P Package on Linux
      • Design Notes
        • Data Sharing
      • Odoo Modules
        • G2P Registry Datashare: RabbitMQ
        • ODK App User Mapping
      • Performance Testing
  • PBMS
    • Features
      • Program Management
        • Role of a Program Manager
        • Program Life Cycle
      • Program Disbursement Cycles
        • 📔User Guides
          • 📔Create Program Fund
          • 📔Create Cycle Manager for a Program
      • Beneficiary Management
        • Beneficiary Registry
          • 📔User Guides
            • 📔Create an Individual Registrant
            • 📔Create a Group and Add Individual Registrants to the Group
            • 📔Assign a Program to a Group
            • 📔Assign a Program to an Individual
        • Beneficiary Registry Configurations
          • 📔User Guides
            • 📔Configure ID Types
            • 📔Configure Registrant Tags
            • 📔Configure Gender Types
            • 📔Configure Relationships
            • 📔Configure Group Types
            • 📔Configure Group Membership Kind
        • Registration
          • 📔User Guides
            • 📔Import CSV File to Registry Module
      • ID Verification
      • Eligibility
        • Proxy Means Test
        • 📔User Guides
          • 📔Create Eligibility Manager Types
            • 📔Configure Default Eligibility Manager
            • 📔Create ID Document Eligibility Manager
            • 📔Create Phone Number Eligibility Manager
          • 📔Configure Proxy Means Test
          • 📔Verify Eligibility of Enrolled Registrants
      • Deduplication
        • 📔User Guides
          • 📔Deduplicate Registrants
          • 📔Create Deduplication Manager Types
            • 📔Configure Default Deduplication Manager
            • 📔Create ID Deduplication Manager
            • 📔Create Phone Number Deduplication
      • Enrolment
        • 📔User Guides
          • 📔Enroll Registrants into Program
          • 📔Auto-Enroll New Registrants into a Program
          • 📔Enroll Eligible Individual Registrants into a Program
      • Entitlement
        • 📔User Guides
          • 📔Multi-Stage Approval
          • 📔Create Entitlement Manager Type
            • 📔Create Default Entitlement Manager
            • 📔Create Voucher Entitlement Manager
            • 📔Configure Cash Entitlement Manager
          • 📔Create Entitlement Voucher Template
          • 📔Configure the Payments File with QR Code
          • 📔Configure Default Cycle Managers
          • 📔Export Beneficiaries Approved Entitlement
      • Disbursement
        • Payment Batches
        • In-Kind Transfer
          • 📔User Guides
            • 📔Create a Product in Inventory
            • 📔Configure In-Kind Entitlement Manager
            • 📔Create and Approve Program Cycle
            • 📔Verify Eligibility of Registrants in a Cycle
        • Digital Cash Transfer
        • e-Voucher
        • 📔User Guides
          • Prepare and Send Payment
      • Self Service Portal
        • 📔User Guides
          • 📔Create Form and Map with Program
          • 📔Configure Login Providers for Beneficiary Portal
          • 📔Self Register Online
      • Document Management
      • Multi-tenancy
      • Notifications
        • 📔User Guides
          • 📔Send Notifications to Individual Registrants
          • 📔Create Notification Manager Types
            • 📔Create SMS Notification Manager
            • 📔Create Email Notification Manager
            • 📔Create Fast2SMS Notification Manager
          • 📔Create Notification Manager under Program
      • Accounting
      • Administration
        • RBAC
          • 📔User Guides
            • 📔Create User and Assign Role
            • 📔Configure Keycloak Authentication Provider for User Log in
        • i18n
      • ODK Importer
        • 📔User Guides
          • 📔Configure and Import ODK Form
          • 📔Import Specific ODK Forms using ODK Instance ID
          • 📔Import Social Registry Data into PBMS
      • MTS Connector
        • 📔User Guides
          • 📔Create MTS Connector
            • 📔Create ODK MTS Connector
            • 📔Create OpenG2P Registry MTS Connector
      • Audit Logs
      • Service Provider Portal
        • 📔User Guides
          • 📔Submit Reimbursement Using the Service Provider Portal
          • 📔Reimburse the Service Provider
      • Interoperability
      • Privacy and Security
      • Periodic Biometric Authentication for Beneficiaries
      • Beneficiary Exit Process
      • Verifiable Credential Issuance
        • 📔User Guides
          • 📔Configure Inji to download Beneficiary VCs
      • Deduplication
      • Manual In-Kind Entitlement
      • Print Disbursement Summary
      • Monitoring & Reporting
        • Logging
      • Priority List
      • Offline Capabilities
      • Grievance Redress Mechanism
    • Versions
    • Developer Zone
      • Odoo Modules
        • G2P Enumerator
        • OpenG2P Registry MTS Connector
        • G2P Documents Store
        • MTS Connector
        • G2P Formio
        • G2P Registry: Rest API Extension Demo
        • G2P Registry: Additional Info REST API
        • G2P Registry: Bank Details Rest API
        • G2P Registry: Additional Info
        • G2P Registry: Membership
        • G2P Registry: Groups
        • G2P Registry: Individual
        • G2P Registry: Base
        • G2P Registry: Rest API
        • G2P Registry: Bank Details
        • G2P Registry: Security
        • G2P Service Provider Beneficiary Management
        • OpenG2P Program Payment (Payment Hub EE)
        • OpenG2P Program Payments: In Files
        • G2P Program : Program Registrant Info Rest API
        • OpenG2P Entitlement: Differential
        • OpenG2P Program: Approval
        • OpenG2P Program: Assessment
        • G2P Program: Registrant Info
        • OpenG2P Program Payment: Simple Mpesa Payment Manager
        • OpenG2P Programs: Cycleless
        • OpenG2P Entitlement: In-Kind
        • G2P Notifications: Wiserv SMS Service Provider
        • G2P: Proxy Means Test
        • G2P Programs: REST API
        • G2P Program Payment (Payment Interoperability Layer)
        • OpenG2P Entitlement: Voucher
        • OpenG2P Programs: Reimbursement
        • OpenG2P Program Payment: Cash
        • OpenG2P Program: Documents
        • OpenG2P Program Payment: G2P Connect Payment Manager
        • OpenG2P Programs: Autoenrol
        • G2P ODK Importer
        • OpenID Connect Authentication
        • G2P Auth: OIDC - Reg ID
        • G2P OpenID VCI: Base
        • G2P OpenID VCI: Programs
        • G2P OpenID VCI: Rest API
        • G2P Program Datashare: RabbitMQ
      • Developer Install on Linux
      • Repositories
        • openg2p-fastapi-common
          • OpenG2P FastAPI Common
          • OpenG2P FastAPI Auth
          • OpenG2P Common: G2P Connect ID Mapper
        • social-payments-account-registry
        • g2p-bridge
        • openg2p-packaging
        • openg2p-security
        • spar-load-test
        • 4sure
        • G2P SelfServicePortal
      • Technology Stack
    • Deployment
      • i18n
      • Installation of Odoo Modules
      • Domain names and Certificates
      • Helm Charts
  • SPAR
    • Features
      • SPAR Mapper
      • SPAR Self Service
      • Privacy & Security
      • Interoperability
      • Performance & Scale
      • Monitoring & Reporting
    • Deployment
      • Domain Names and Certificates
      • Helm Charts
    • 📔User Guides
      • 📔Link FA (Self Service)
      • 📔Link FA (Admin)
    • Development
      • Jira Board
      • Testing
        • Unit Testing
        • Functional Testing
        • Performance Testing
          • Mapper
            • Resolve API
            • Link API
            • Unlink API
            • Update API
      • Developer Install
        • SPAR Mapper API
        • SPAR Self Service API
        • SPAR Self Service UI
      • Repositories
      • API Reference
      • Tech Guides
    • Releases
      • 1.0.0
      • 1.1.0
  • G2P Bridge
    • Features
      • Extensibility - Connect to Sponsor Banks
      • Account Mapper Resolution
      • Reconciliation with Sponsor Bank
      • Scaling for High Volumes
      • Interoperability
      • Privacy & Security
      • Monitoring & Reporting
    • Deployment
      • Deployment of G2P Bridge
      • Deployment of Example Bank
      • Bank Connector Interface Guide
      • PBMS Configuration
    • Developer Zone
      • Design
        • IN APIs from PBMS
          • create_disbursement_envelope
          • cancel_disbursement_envelope
          • create_disbursements
          • cancel_disbursements
          • get_disbursement_envelope_status
          • get_disbursement_status
        • OUT APIs to Mapper
          • resolve
        • OUT APIs to Bank
          • check_funds_with_bank
          • block_funds_with_bank
          • disburse_funds_from_bank
        • IN APIs from Bank
          • upload_mt940
        • Helper Tables
          • benefit_program_configuration
        • Configuration parameters
        • Bank Connectors
        • Physical Organization
        • Example Bank
          • example-bank-models
          • example-bank-api
          • example-bank-celery
      • Testing
        • Unit Testing
        • Functional Testing
        • Performance Testing
      • Repositories
      • Developer Install
        • G2P Bridge
        • Example Bank
      • API Reference
    • Tech Guides
    • User Guides
    • Releases
      • 1.0.2
  • PBMS-Gen2
    • Developer Zone
      • Design
        • Concept
        • PBMS (Odoo)
  • Utilities and Tools
    • ODK
      • 📔User Guides
        • 📔Create a Project for a Program
        • 📔Create a Form
        • 📔Upload a Form
        • 📔Upload revised Form
        • 📔Test a Form
        • 📔Publish a Form
        • 📔Provide Form Access to Field Agent
        • 📔Download a Form on ODK Collect
        • 📔Delete a Form
        • 📔Register Offline
    • 4Sure Verifier App
      • Installation Guide for 4Sure Application
      • 📔User Guides
        • 📔Verify Digital Credentials using 4Sure Application
        • 📔Verify and Populate the form in ODK Collect using 4Sure Application
      • 4Sure Test Summary
    • Smartscanner
      • 📔User Guides
    • Registration Tool Kit
    • Unified Conversation Agent (UCA)
      • Modal Context Protocol(MCP)
      • Model Context Protocol (MCP) Implementation in UCA
      • Social Benefits Assistant with FastMCP
  • Testing
    • Test Workflow
    • Automation Framework
  • Monitoring and Reporting
    • Apache Superset
    • Reporting Framework
      • 📔User Guides
        • 📔Connector Creation Guide
        • 📔Dashboards Creation Guide
        • 📔Installation & Troubleshooting
      • Kafka Connect Transform Reference
    • System Logging
    • System Health
  • Privacy and Security
    • Key Manager
  • Data Share
    • OpenG2P - IUDX
  • Interoperability
  • Deployment
    • Base Infrastructure
      • Wireguard Bastion
        • Install WireGuard Client on Android Device
        • Wireguard Access to Users
        • Install WireGuard Client on Desktop
      • NFS Server
      • Rancher Cluster
      • OpenG2P Cluster
        • Kubernetes
          • Firewall
          • Istio
          • Adding Nodes to Cluster
          • Deleting Nodes from Cluster
        • Prometheus & Grafana
        • Fluentd & OpenSearch
          • DEPRECATED - OpenSearch
        • Landing Page For OpenG2P
      • Load Balancer
        • Nginx
        • AWS
    • Resource Requirements
    • Helm Charts
    • Upgrades
    • Production
    • OpenG2P In a Box
    • Packaging
    • Versioning
    • Additional Guides
      • Automatic Build and Upload of Private Dockers
      • Generate SSL Certificates using Letsencrypt
      • Packaging Odoo based Docker
      • AWS
        • Create ACM Certificate on AWS
        • Create Security Group on AWS
        • Domain mapping on AWS Route53
        • Make Environment Publicly Accessible using AWS LB Configuration
      • Private Access Channel
      • Odoo Post Install Configuration
      • Pulling Docker from Private Repository on Docker Hub
      • Keycloak Client Creation
      • Troubleshooting: "fsnotify watcher" warning
      • Uninstalling Applications from Rancher UI
      • Access a Database from Outside the Cluster
      • Configure External Database to Connect OpenG2P Environment
      • Configure IPSec VPN Gateway to Connect to External Systems using Strongswan
      • Troubleshooting
        • PostgreSQL Database not Starting due to Replication Checkpoint Error
        • No Space Left on the Device Warning
      • Restart Deployment or StatefulSets to Redistribute Pods across Nodes
      • Rerun Jobs in Kubernetes Cluster
      • Finding URLs in the System
      • Transitioning PostgreSQL From Docker on K8s to Standalone PostgreSQL
      • Restore a PVC from an NFS Folder and Attach it to a Pod
      • View System Logs on the OpenSearch Dashboard
      • Set up Slack alerts for a Kubernetes cluster
      • Importing Dashboards on the Superset UI for OpenG2P Applications
      • Scaling Down an Environment to Optimize Resource Usage
      • Kubernetes Master Nodes
      • Enabling Keycloak User Self-Registration
      • Automating Cache Cleanup on K8s Cluster Nodes with Cron Job
      • Set Up Slack Alerts for a Standalone Node using Netdata
    • Persistent Storage
      • Resizing Persistent Volume Claim in Kubernetes Cluster
  • 📒Guides
    • 📔User Guides
      • PBMS
        • 📔Create Program
        • 📔Configure Payment Manager in Program
        • 📔Create Eligibility Manager under Program
        • 📔Create Program Manager for a Program
        • 📔Create Manager Type
          • 📔Create Payment Manager Types
            • 📔Create Payment Hub EE Payment Manager
            • 📔Create Payment Interoperability Layer Payment Manager
            • 📔Create Default Payment Manager
            • 📔Create Cash Payment Manager
            • 📔Create File Payment Manager
        • 📔Configure Entitlement Manager under Program
        • 📔Archive, Delete, End, and Re-activate a Program
        • 📔Configure Default Program Manager
        • 📔Create Deduplication Manager under Program
    • Documentation Guides
      • Documentation Guidelines
        • Embed a Miro diagram
      • OpenG2P Module Doc Template
  • Use Cases
    • Farmer Registry
      • Reference Design: Farmer Registry
  • Releases
    • 1.1.0
      • Release Notes
  • License
    • OpenG2P Support Policy
  • Community
    • Contributing
    • Code of Conduct
  • Blogs
    • OpenG2P and SDG Goals
Powered by GitBook
LogoLogo

Copyright © 2024 OpenG2P. This work is licensed under Creative Commons Attribution International LicenseCC-BY-4.0 unless otherwise noted.

On this page
  • Introduction
  • Technical concepts
  • Installation
  • Recommended project structure
  • Usage guide
  • App.py
  • Configuration
  • Controllers
  • Services
  • Components
  • Logging
  • Models
  • Exceptions
  • Additional Configuration
  • Source code

Was this helpful?

  1. PBMS
  2. Developer Zone
  3. Repositories
  4. openg2p-fastapi-common

OpenG2P FastAPI Common

Previousopeng2p-fastapi-commonNextOpenG2P FastAPI Auth

Last updated 9 months ago

Was this helpful?

Introduction

This is a Python package that can be used as a library to bootstrap REST API services, based on . This page describes different concepts within the library and instructions on how to use it.

Technical concepts

This package/library contains basic components, like Configuration helpers, Logging helpers, DB ORM helpers, Base Initializers, etc that are required to bootstrap a basic service built using Python and FastAPI. A detailed description is given below.

Name
Description

Component

  • A Component is an object that gets stored in a global registry (called Component Registry) when initialized.

  • Components are usually only initialized once mostly inside an Initializer class. Once initialized in Initializer, they can be obtained using the class method; <ComponentClass>.get_component().

  • A name (optional) can be given to instances of Components so that they can be retrieved using that name if there are multiple instances of a Component. <ComponentClass>.get_component("mycomp").

  • BaseComponent is the base Class for Components.

Service

  • A Service is also a Component that usually contains some logic that is executed inside a Controller.

  • Use <ServiceClass>.get_component() to retrieve a service.

  • BaseService is the base Class for Services.

  • Service is technically the same as Component. Prefer Service over Component when defining new.

Controller

  • In the init method of a Controller, the API Routes need to be manually added.

  • Use <ControllerClass>.get_component() to retrieve a Controller.

  • BaseController is the base Class for Controllers.

Settings

  • Settings, based on Pydantic's BaseSettings, establishes configuration options.

  • Configuration Parameters defined inside Settings can be loaded through Env variables / .env file.

  • Settings Class in config can be used as the base class by other Settings classes to inherit.

BaseORMModel

  • BaseORMModel is an SQLAlchemy ORM Model, that can be used as a base class for other ORM Classes to inherit.

BaseExceptionHandler

  • BaseExceptionHandler is an Exception Handler Implementation that uses FastAPI Exception Handler at the base and handles extra exceptions defined in this module, mainly BaseAppException.

  • This can also be extended to further handle custom Exceptions when defined.

Initializer

  • Initializer is a class that initializes all the components, services, controllers, configs, loggers, etc along with any additional Components of a particular Python Package/Module.

  • The Components have to be individually initialized inside the init method of an Initializer.

Installation

This section describes instructions for installing the package. Primarily intended for developers using this module to build their own projects.

  • Install python3 for your environment.

  • Set up a virtualenv in your project directory. Using:

    python3 -n venv .venv
    source .venv/bin/activate
  • Clone .

  • Then Install the common package using pip:

    pip install -e <path-to-cloned-common-repo>/openg2p-fastapi-common

Recommended project structure

Usage guide

This section describes instructions for using the package/library. Primarily intended for developers using this module to build their own projects.

App.py

  • The app.py file in the project acts as the main file which initializes all the components of the project. It should contain an Initializer.

  • Initialize the Components (like Services, Controllers, etc.) inside the initialize method of the Initializer. Example

    # ruff: noqa: E402
    
    from .config import Settings
    
    _config = Settings.get_config()
    
    from openg2p_fastapi_common.app import Initializer
    
    from .services.ping_service import PingService
    from .controllers.ping_controller import PingController
    
    
    class PingInitializer(Initializer):
        def initialize(self):
            PingService()
            PingController().post_init()
  • Note: If the Initializer is only supposed to be used by external modules to inherit/extend/use. Then do not run super().initialize() inside the initialize method. If the Initializer is the main Initializer that sets up the FastAPI apps etc then run super().initialize() inside the initialize method.

  • Note: Due to a limitation in the way the config is set up, the Settings.get_config() needs to be put at the beginning of the app.py (only applies to app.py), before importing other Initializers. If your Linters/Code Formatters are throwing up an E402 error, ignore the error at the beginning of app.py. Check the above example.

Configuration

  • If you are using the template given above, use the config file present in the src folder of your Python package. If not, create a config.py file in your project that looks like this.

    from openg2p_fastapi_common.config import Settings
    from pydantic_settings import SettingsConfigDict
    
    
    class Settings(Settings):
        model_config = SettingsConfigDict(
            env_prefix="myproject_", env_file=".env", extra="allow"
        )
  • To define configuration parameters for your project, add the properties to the above Settings class defined in config.py. Example

    class Settings(AuthSettings, Settings):
        ...
        m_param_a : str = "default_value"
        m_param_b : int = 12
  • The parameters defined here can be loaded through environment variables or .env file. The environment variables can be case insensitive. For example

    myproject_m_param_a="loaded_value"
    MYPROEJCT_M_PARAM_B="10456"
    • The environment variable prefix, myproject_ in the above example, can be configured under model_config of Settings class, under env_prefix.

  • To use this config in other components of your project like models/controllers/services, etc. use the get_config class method of the above Settings class. Example inside a controller file

    ...
    from .config import Settings
    
    _config = Settings.get_config()
    
    
    class PingController(BaseController):
        ...
        
        def get_ping(self):
            ...
            print(_config.m_param_a)
            ...

Controllers

  • To add more APIs to your project, create controllers in the controllers directory.

  • Add each API route using the add_api_route method of the router. Example ping_controller.py.

    from openg2p_fastapi_common.controller import BaseController
    
    from .config import Settings
    
    _config = Settings.get_config()
    
    
    class PingController(BaseController):
        def __init__(self, name="", **kwargs):
            super().__init__(name, **kwargs)
    
            self.router.tags += ["ping"]
    
            self.router.add_api_route(
                "/ping",
                self.get_ping,
                methods=["GET"],
            )
    
        async def get_ping(self):
            return "pong"
  • ...
    from .controllers.ping_controller import PingController
    
    class PingInitializer(Initializer):
        def __init__(self):
            ...
            PingController().post_init()
  • A Controller will automatically initialize Response models for the APIs for the following HTTP Codes: 401, 403, 404, and 500 (with the ErrorListResponse response model defined in this module). These can be changed/updated accordingly.

Services

  • Create Services in the services directory similar to a Controller.

  • Example

    from openg2p_fastapi_common.service import BaseService
    
    from .config import Settings
    
    _config = Settings.get_config()
    
    
    class PingService(BaseService):
        def ping(self, pong: str):
            return _config.m_param_a + " " + pong

Components

  • To retrieve an instance of a Component (Service, Controller, etc) use Component.get_component().

  • Example in PingController if you want to retrieve the PingService.

    ...
    from .services.ping_service import PingService
    ...
    
    
    class PingController(BaseController):
        def __init__(self, name="", **kwargs):
            super().__init__(name, **kwargs)
            ...
    
            self.ping_service = PingService.get_component()
        
        async def get_ping(self):
            return self.ping_service.ping("pong")

Logging

  • This can be modified using the init_logger method of an Initializer.

Models

  • Use BaseORMModel as the base class for your ORM Model.

    • Use BaseORMModelWithID as the base class, to automatically add id and active fields to the ORM class, along with quick helper classmethods to get an object using id. Example <MyORMModel>.get_by_id(id) .

    • Use BaseORMModelWithTimes as the base class, to automatically add created_at and updated_at along with features of BaseORMModelWithID.

  • from openg2p_fastapi_common.context import dbengine
    from openg2p_fastapi_common.models import BaseORMModelWithTimes
    from sqlalchemy.ext.asyncio import async_sessionmaker
    from sqlalchemy.orm import Mapped, mapped_column
    from sqlalchemy import String, select
    
    class MyORMModel(BaseORMModelWithTimes):
        name: Mapped[str] = mapped_column(String())
        
        @classmethod
        def get_by_name(cls, name: str):
            response = []
            async_session_maker = async_sessionmaker(dbengine.get())
            async with async_session_maker() as session:
                stmt = select(cls).where(cls.name==name).order_by(cls.id.asc())
                result = await session.execute(stmt)
                response = list(result.scalars())
            return response

Exceptions

The following Exceptions are defined by this module. When these exceptions are raised in code, they are caught and handled by BaseExceptionHandler.

The HTTP Response Payload looks like this when the following exceptions are raised. (The HTTP Response Status code is defined according to the Exception).

{
    "errors": [
        {
            "code": "<error_code from Exception>",
            "message": "<error_message from Exception>",
        }
    ]
}
Exception
Description

UnauthorizedError

Raise this to return 401 Unauthorized HTTP response. UnauthorizedError derives from BaseAppException.

Default error_code is G2P-AUT-401.

Default error_message is Unauthorized.

Default http_status_code is 401.

ForbiddenError

Raise this to return 403 Forbidden HTTP response. ForbiddenError derives from BaseAppException.

Default error_code is G2P-AUT-403.

Default error_message is Forbidden.

Default http_status_code is 403.

BadRequestError

Raise this to return 400 Bad Request HTTP response. BadRequestError derives from BaseAppException.

Default error_code is G2P-REQ-400.

Default error_message is Bad Request.

Default http_status_code is 400.

NotFoundError

Raise this to return 404 Not Found HTTP response. BadRequestError derives from BaseAppException.

Default error_code is G2P-REQ-404.

Default error_message is Not Found.

Default http_status_code is 404.

InternalServerError

Raise this to return 500 Internal Server Error HTTP response. InternalServerError derives from BaseAppException.

Default error_code is G2P-REQ-500.

Default error_message is Internal Server Error.

Default http_status_code is 500.

BaseAppException

BaseAppException is the parent for the custom exceptions. It takes an error_code , error_message and http_status_code arguments. Default http_status_code is 500. If this is manually raised in code, an error response will be returned on the API Call with the given error code, and error message, and HTTP Status will be set to the given status code.

Additional Configuration

Property
Description
Default Value

host

Host/IP to which the HTTP server should bind to.

0.0.0.0

port

Port on which the server HTTP should run.

8000

logging_level

Logging Level. Available values DEBUG, INFO, WARN, ERROR and CRITICAL.

INFO

logging_file_name

Path to a file where the log should should be stored. If left empty, no file logging. Stdout logging is enabled by default.

openapi_title

Title in OpenAPI Definition. This is the title field in openapi.json generated by FastAPI. Hence also present on Swagger and API Docs.

Common

openapi_description

Description in OpenAPI

openapi_version

Version in OpenAPI

1.0.0

openapi_contact_url

Contact URL in OpenAPI

https://www.openg2p.org/

openapi_contact_email

Contact Email in OpenAPI

info@openg2p.org

openapi_license_name

License Name in OpenAPI

Mozilla Public License 2.0

openapi_license_url

License URL in OpenAPI

https://www.mozilla.org/en-US/MPL/2.0/

db_datasource

This is the property used by SQLALchemy for DB datasource. If left empty, this will be constructed, using the following db properties, like the following:

db_driver

Driver to use while connecting to Database. Configure this based on the Database being used. If using PostgreSQL, leave it as default.

postgresql+asyncpg

db_hostname

Database Host/IP

localhost

db_port

Database Port

5432

db_dbname

Database Name

db_username

Database Authentication Username

db_password

Database Authentication Password

db_logging

Database Logging. If true, all the database operations being made will be put out in the server logs. Useful while debugging.

false

Source code

A Controller is also a Component, that contains a and API Routes inside it. The APIRouter and APIs get initialized when the Controller is initialized.

Controllers also have a post_init method that adds the APIRouter and APIs into a global . So inside an Initializer, the post_init method can be called immediately after the Controller is initialized.

Follow the instructions here , to set up a repository with the given template and folder structure.

This Settings class derives from .

Refer to to see the configuration properties already available in the base Settings class.

Initialize the Controller, preferably in an Initializer like given . It is important to run the post_init method of the Controller after initializing it since that will add the API Router of the Controller to the FastAPI App. Example

Initialize the Service in the Initializer like given .

Get the logger using logging.getLogger(__name__) . This logger initializes JSON logging, using .

Define and ORM Models (based on ) inside the models directory.

This module also uses the . Follow the link to understand how to use SQLAlchemy and async conventions to interact with the database. Example:

The following configuration properties are already present in the base Settings class mentioned in .

The following properties can also be set through the environment variables, but the env_prefix configured in your project's config Settings will have to be used, as mentioned . Example myproject_logging_level=DEBUG .

OpenG2P FastAPI Common Module Source Code -

from openg2p_fastapi_common.errors.http_errors import UnauthorizedError
from openg2p_fastapi_common.errors.http_errors import ForbiddenError
from openg2p_fastapi_common.errors.http_errors import BadRequestError
from openg2p_fastapi_common.errors.http_errors import NotFoundError
from openg2p_fastapi_common.errors.http_errors import InternalServerError
from openg2p_fastapi_common.errors import BaseAppException
f"{db_driver}://{db_username}:{db_password}@{db_hostname}:{db_port}/{db_dbname}"
FastAPI
openg2p-fastapi-common
https://github.com/OpenG2P/openg2p-fastapi-template
pydantic_settings 's BaseSettings
json-logging
Pydantic Models
SQLAlcehmy 2.0 ORM
AsyncIO Extension of SQLAlchemy 2.0 ORM
https://github.com/OpenG2P/openg2p-fastapi-common/tree/develop/openg2p-fastapi-common
Additional Configuration
above
above
Configuration Guide
above
FastAPI APIRouter
FastAPI App