Skip to main content

III API base

PyPI - Version PyPI - Python Version
Downloads Weekly downloads Monthly downloads
Hatch project linting - Ruff

III FastAPI Common base
Go to pypi now


Usage

Config

The later config will override the previous one.

This table shows the predefined environment variables.

Keyword Type Default Description
DEBUG boolean false To set the logging as DEBUG state, you can pass debug=True to application too.
RELOAD boolean false To auto reload the FastAPI application, you can pass reload=True to run too.
APP_NAME string Backend API The application name use on FastAPI.
from pathlib import Path

from api_helper.config import load_config

# Load config
load_config(Path(__file__).parent / ".env")

# Load default config in the directory (.env)
load_config(Path(__file__).parent)

FastAPI example

To config the FastAPI by env, read the Config section.

from pathlib import Path

from api_helper import FastAPI, success_response

app: FastAPI = FastAPI(base_folder=Path(__file__).parent)
# Optional to setup sentry
app.setup_sentry("sentry_dsn")


@app.get("/")
def home():
    return success_response("Hello, World!")


# Start the app and enjoy
app.run("127.0.0.1", 5000)

# Start the app with OpenAPI, for example
app.run(show_swagger=True)

Use FastAPI with auto-reload

To use the reload method, you need to pass reload=True and app="main:app" to the run method.
If you don't pass them, the reload will not work. See the sample code below.

from pathlib import Path

from api_helper import FastAPI

# Must declared before running into main code block
app: FastAPI = FastAPI(base_folder=Path(__file__).parent.parent)

if __name__ == "__main__":
    # Pass the app as a string to uvicorn.run to enable auto-reload
    app.run(app="test:app", reload=True)

Custom Logger Format

If you want to customize the Logger format, you can pass log_builder to the FastAPI object.
The following example shows how to customize the logger format.
See below sample for more information.

from pathlib import Path

from api_helper import FastAPI
from api_helper.config import LoggerBuilder

# To customize the logger format, you can pass the log_builder to FastAPI
log_builder: LoggerBuilder = LoggerBuilder(Path(__file__).parent)
log_builder.formatters = {}  # For example, we change the formatter to empty
app: FastAPI = FastAPI(base_folder=Path(__file__).parent, log_builder=log_builder)

# Or if you prefer the default, you can extend the default formatter
# For example, you can change the root level to DEBUG with default formatter
log_builder: LoggerBuilder = LoggerBuilder(Path(__file__).parent, config={"root": {"level": "DEBUG"}})
app: FastAPI = FastAPI(base_folder=Path(__file__).parent, log_builder=log_builder)

# Or pass as parameter start with the `logging_` keyword, it will be passed to the LoggerBuilder
# It is the same as the previous example
app: FastAPI = FastAPI(base_folder=Path(__file__).parent, logging_config={"root": {"level": "DEBUG"}})

Response

Expose the SuccessModel and ErrorModel to represent the response.

sample:

from api_helper.generic import SuccessModel
from api_helper import success_response
from fastapi import Response


# Basic usage
@route.get("/", response_model=SuccessModel)
def get() -> Response:
    return success_response("Hello, World!")


# If you have custom data, you can pass it to the success_response
@route.get("/", response_model=SuccessModel[list[User]])
def get() -> Response:
    return success_response(session.exec(select(User)).all())


# If you use paginate
@route.get("/items", response_model=SuccessModel[Pagination[User]])
def list_items() -> Response:
    return success_response(paginate(session=session, query=select(User)))

Database

Alembic

The Alembic class is an easy way to check Alembic status by code.
You can use the Alembic class to check the Alembic status.

properties:

  • current: The current revision. If not current, return empty string.
  • head: The head revision. If not head, return empty string.
  • upgradeable: If the current is not head, return True.
  • scrip_direrctory: The ScriptDirectory object, used by alembic.

functions:

  • get_config(): Get the Alembic config object. You can pass it to alembic env.py file.
  • upgrade(): Upgrade to the revision, if not provided, it will upgrade to the head.

SQLModel Pagination

To reduce the boilerplate code, you can use the paginate function to get the pagination object.

parameters:

  • session: The session object from the database.
  • query: The query object from the database. It can use where, limit, offset, etc.
  • page: The page number, default is 1.
  • per_page: The number of items per page, default is 10.

sample code:

from api_helper.database import paginate
from sqlmodel import SQLModel


# For example, you have a SQLModel
class User(SQLModel, table=True):
    id: int
    name: str


# You can use the paginate function to get the pagination
# The paginate function will return the pagination object
pagination = paginate(session=session, query=select(User))

# You will get something like this
{
    "items": [],
    "pagination": {
        "total": 0,
        "page": 1,
        "pages": 1,
        "per_page": 10,
        "prev": None,
        "next": None,
    }
}

For fastAPI routes, you can also use common_query as a quick dependency.

from api_helper import success_response
from api_helper.database import common_query
from api_helper.database import paginate
from api_helper.types import PaginateQuery

from fastapi import Depends
from fastapi import Response

@route.get("/sample")
def list_items(
    *,
    session: Session = Depends(get_session),
    # Here, we use common_query as a dependency, it provides the page and per_page query
    page_query: PaginateQuery = Depends(common_query),
) -> Response:
    return success_response(
        paginate(session=session, query=select(DiffItem), page=page_query.page, per_page=page_query.per_page)
    )

Changelogs

0.1.4

bugs:

  • Fix MRO error on UUIDModel and TimestampModel.

Breaking changes:

  • Rename database.model to database.mixin and related class names.

0.1.3

feat:

  • Add UUIDModel, TimestampModel for sqlmodel more easier to use.

0.1.2

feat:

  • Add common_query function for common use query. It can use like normal Depends.

0.1.1

bugs:

  • alembic object won't get the sql_str property correctly.

0.1.0

Feats:

  • Add new alembic class for easier to get alembic status, see the Alembic section for more information.
  • Add paginate function for those who use SQLmodel, see the SQLModel section for more information.
  • Add SuccessModel and ErrorModel for easier to return the response, see the Response section for more information.
  • Add Singleton pattern to avoid multiple instances.

Chore:

  • Move errors into module.
  • Update database requirements.

Metadata

Release files for iii-api-helper 0.1.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for iii-api-helper 0.1.5
File Size Uploaded Provenance
iii_api_helper-0.1.5.tar.gz 23.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for iii-api-helper 0.1.5
File Interpreter ABI Platform
iii_api_helper-0.1.5-py3-none-any.whl Python 3 none any Details

Total release size: 42.3 kB

Release files / iii_api_helper-0.1.5.tar.gz

Download URL iii_api_helper-0.1.5.tar.gz
Size 23.2 kB
Tags Source
SHA-256 checksum
How to use checksums
85123d4cc2f9f9295353b03a4a0dd04fdedc34c6fb03dff84beff76f41c4a693
BLAKE2b-256 checksum
How to use checksums
2578183e6c61faca9af80cd4ee3423a22c96fea4df1efc3639ec690e32950312
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.27.0

Release files / iii_api_helper-0.1.5-py3-none-any.whl

Download URL iii_api_helper-0.1.5-py3-none-any.whl
Size 19.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
55014c53ea983ff343696b632f063621004cacb47b94ef8c6b02395c96f75c60
BLAKE2b-256 checksum
How to use checksums
fc0362ee15a27460255eb865c2fe465bed876417e75757bdcce7a32c216d4af8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.27.0

Security for iii-api-helper 0.1.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.5 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page