Async and Sync wrapper client around httpx, fastapi, date stuff

Overview

lazyapi

Async and Sync wrapper client around httpx, fastapi, and datetime stuff.


Motivation

This library is forked from an internal project that works with a lot of backend APIs, namely interacting with kubernetes's API. In certain cases, you want to use sync where async isnt suitable, but managing two seperate sync / async client can be annoying, especially when you aren't initializing from async at the start.

This project aims to solve a few problems:

  • Enables both sync and async REST calls from the same client.

  • Improves upon serialization/deserialization over standard json library by using simdjson.

  • Enables dynamic dataclass creation from responses via lazycls that are based on pydantic BaseModel.

  • Work with Timestamp / Datetime much quicker and simpler.

  • Manipulate response objects as efficiently as possible.

  • Wrapper functions for fastapi to enable quick api creation.


Quickstart

pip install --upgrade lazyapi
HttpResponse(resp= , clientType='sync', method='get', timestamp=datetime.datetime(2021, 12, 1, 7, 55, 10, 478544, tzinfo=datetime.timezone.utc)) class HttpResponse(BaseCls): resp: Response clientType: str = 'sync' method: str = 'get' timestamp: str = Field(default_factory=get_timestamp_utc) DefaultHeaders = { 'Accept': 'application/json', 'Content-Type': 'application/json' } --- Client Configs from Env Variables class HttpCfg: timeout = envToFloat('HTTPX_TIMEOUT', 30.0) keep_alive = envToInt('HTTPX_KEEPALIVE', 50) max_connect = envToInt('HTTPX_MAXCONNECT', 200) headers = envToDict('HTTPX_HEADERS', default=DefaultHeaders) class AsyncHttpCfg: timeout = envToFloat('HTTPX_ASYNC_TIMEOUT', 30.0) keep_alive = envToInt('HTTPX_ASYNC_KEEPALIVE', 50) max_connect = envToInt('HTTPX_ASYNC_MAXCONNECT', 200) headers = envToDict('HTTPX_ASYNC_HEADERS', default=DefaultHeaders) """ ">
from lazyapi import APIClient

# Allows initialization of the client from sync call. 
# The client has both async and sync call methods.
apiclient = APIClient(
    base_url = 'https://google.com',
    headers = {},
    module_name = 'customlib',
)

# All requests will be routed through the base_url
# Sync Method
resp = apiclient.get(path='/search?...', **kwargs)

# Async Method
resp = await apiclient.async_get(path='/search?...', **kwargs)

"""
Both yield the same results, only differing in the clientType = sync | async
The underlying classes are auto-generated from Pydantic BaseModels, so anything you can do with Pydantic Models, you can do with these.

> HttpResponse(resp=
    
     , clientType='sync', method='get', timestamp=datetime.datetime(2021, 12, 1, 7, 55, 10, 478544, tzinfo=datetime.timezone.utc))
    

class HttpResponse(BaseCls):
    resp: Response
    clientType: str = 'sync'
    method: str = 'get'
    timestamp: str = Field(default_factory=get_timestamp_utc)

DefaultHeaders = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

---
Client Configs from Env Variables

class HttpCfg:
    timeout = envToFloat('HTTPX_TIMEOUT', 30.0)
    keep_alive = envToInt('HTTPX_KEEPALIVE', 50)
    max_connect = envToInt('HTTPX_MAXCONNECT', 200)
    headers = envToDict('HTTPX_HEADERS', default=DefaultHeaders)

class AsyncHttpCfg:
    timeout = envToFloat('HTTPX_ASYNC_TIMEOUT', 30.0)
    keep_alive = envToInt('HTTPX_ASYNC_KEEPALIVE', 50)
    max_connect = envToInt('HTTPX_ASYNC_MAXCONNECT', 200)
    headers = envToDict('HTTPX_ASYNC_HEADERS', default=DefaultHeaders)

"""

API Specific Features

API Responses

Responses returned from APIClient are of lazyapi.classes.HttpResponse classes which wraps httpx.response in a BaseModel to do response validation, and interfacing with the response such as:

  • .is_error -> bool

  • .is_redirect -> bool

  • .data -> resp.json()

  • .data_obj -> SimdJson.Object / SimdJson.Array

  • .data_cls -> lazycls.LazyCls

  • .timestamp -> str with utc timestamp of request

Time/Datetime Functions

lazyapi.timez: Includes a multitude of datetime based functions to work with timestamp / time / duration.

  • TIMEZONE_DESIRED env to set the desired Timezone Default: America/Chicago

  • TIMEZONE_FORMAT env to set the desired Timezone parse. Default: %Y-%m-%dT%H:%M:%SZ

  • TimezCfg class can be modified based on above two variables.

  • get_timestamp: creates a str based timestamp using local TZ

  • get_timestamp_tz: creates a str based timestamp using the desired TZ

  • get_timestamp_utc: creates a str based timestamp using UTC

  • timer: Simple timer function

  • dtime: Get a datetime object. If no datetime obj is given, returns datetime.now(), otherwise will get the difference

  • get_dtime_secs: converts a datetime object to total num secs.

  • get_dtime_str: Converts a datetime object to a string. If no datetime obj is given, returns datetime.now() converted into desired str format

  • get_dtime_iso: attempts to standardize a datetime obj from existing tz into an iso/desired-formatted datetime

  • dtime_parse: attempts to parse a string, timestamp, etc. into a datetime obj

  • dtime_diff: gets the difference between two datetime objects.

FastAPI wrapper functions

Primarily used to create subapp mounts behind the primary fastapi app.

PlainTextResponse: return PlainTextResponse(content='ok') app.mount('/subapp', subapp) if __name__ == '__main__': import uvicorn uvicorn.run("main:app") """ Now you can expect the route at /subapp/healthz """ ">
from lazyapi import create_fastapi, FastAPICfg

"""
class FastAPICfg:
    app_title = envToStr('FASTAPI_TITLE', 'LazyAPI')
    app_desc = envToStr('FASTAPI_DESC', 'Just a LazyAPI Backend')
    app_version = envToStr('FASTAPI_VERSION', 'v0.0.1')
    include_middleware = envToBool('FASTAPI_MIDDLEWARE', 'true')
    allow_origins = envToList('FASTAPI_ALLOW_ORIGINS', default=["*"])
    allow_methods = envToList('FASTAPI_ALLOW_METHODS', default=["*"])
    allow_headers = envToList('FASTAPI_ALLOW_HEADERS', default=["*"])
    allow_credentials = envToBool('FASTAPI_ALLOW_CREDENTIALS', 'true')

"""
app = create_fastapiapp_name: str, title: str = None, desc: str = None, version: str = None)
subapp = create_fastapi(app_name: 'subapp')

@subapp.get('/healthz')
async def healthcheck() -> PlainTextResponse:
    return PlainTextResponse(content='ok')


app.mount('/subapp', subapp)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app")

"""
Now you can expect the route at
/subapp/healthz


"""
You might also like...
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

 Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions
Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions

Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions To learn more about this project: medium blog post The goal of this proje

REST API with FastAPI and SQLite3.
REST API with FastAPI and SQLite3.

REST API with FastAPI and SQLite3

Example of using FastAPI and MongoDB database.

FastAPI Todo Application Example of using FastAPI and MangoDB database. 💡 Prerequisites Python ⚙️ Build & Run The first thing to do is to clone the r

Basic FastAPI starter with GraphQL, Docker, and MongoDB configurations.

FastAPI + GraphQL Starter A python starter project using FastAPI and GraphQL. This project leverages docker for containerization and provides the scri

FastAPI Learning Example,对应中文视频学习教程:https://space.bilibili.com/396891097

视频教学地址 中文学习教程 1、本教程每一个案例都可以独立跑,前提是安装好依赖包。 2、本教程并未按照官方教程顺序,而是按照实际使用顺序编排。 Video Teaching Address FastAPI Learning Example 1.Each case in this tutorial c

🤪 FastAPI + Vue构建的Mall项目后台管理

Mall项目后台管理 前段时间学习Vue写了一个移动端项目 https://www.charmcode.cn/app/mall/home 然后教程到此就结束了, 我就总感觉少点什么,计划自己着手写一套后台管理。 相关项目 移动端Mall项目源码(Vue构建): https://github.com/

FastAPI on Google Cloud Run

cloudrun-fastapi Boilerplate for running FastAPI on Google Cloud Run with Google Cloud Build for deployment. For all documentation visit the docs fold

FastAPI + Django experiment

django-fastapi-example This is an experiment to demonstrate one potential way of running FastAPI with Django. It won't be actively maintained. If you'

Releases(v0.0.2)
Owner
Chief Architect @ Growth Engine
Adds integration of the Jinja template language to FastAPI.

fastapi-jinja Adds integration of the Jinja template language to FastAPI. This is inspired and based off fastapi-chamelon by Mike Kennedy. Check that

Marc Brooks 58 Nov 29, 2022
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 04, 2023
Lung Segmentation with fastapi

Lung Segmentation with fastapi This app uses FastAPI as backend. Usage for app.py First install required libraries by running: pip install -r requirem

Pejman Samadi 0 Sep 20, 2022
sample web application built with FastAPI + uvicorn

SPARKY Sample web application built with FastAPI & Python 3.8 shows simple Flask-like structure with a Bootstrap template index.html also has a backgr

mrx 21 Jan 03, 2022
Piccolo Admin provides a simple yet powerful admin interface on top of Piccolo tables

Piccolo Admin Piccolo Admin provides a simple yet powerful admin interface on top of Piccolo tables - allowing you to easily add / edit / filter your

188 Jan 09, 2023
Mnist API server w/ FastAPI

Mnist API server w/ FastAPI

Jinwoo Park (Curt) 8 Feb 08, 2022
API & Webapp to answer questions about COVID-19. Using NLP (Question Answering) and trusted data sources.

This open source project serves two purposes. Collection and evaluation of a Question Answering dataset to improve existing QA/search methods - COVID-

deepset 329 Nov 10, 2022
Social Distancing Detector using deep learning and capable to run on edge AI devices such as NVIDIA Jetson, Google Coral, and more.

Smart Social Distancing Smart Social Distancing Introduction Getting Started Prerequisites Usage Processor Optional Parameters Configuring AWS credent

Neuralet 129 Dec 12, 2022
📦 Autowiring dependency injection container for python 3

Lagom - Dependency injection container What Lagom is a dependency injection container designed to give you "just enough" help with building your depen

Steve B 146 Dec 29, 2022
ASGI middleware for authentication, rate limiting, and building CRUD endpoints.

Piccolo API Utilities for easily exposing Piccolo models as REST endpoints in ASGI apps, such as Starlette and FastAPI. Includes a bunch of useful ASG

81 Dec 09, 2022
The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

Bruno Rocha 251 Jan 09, 2023
Twitter API with fastAPI

Twitter API with fastAPI Content Forms Cookies and headers management Files edition Status codes HTTPExceptions Docstrings or documentation Deprecate

Juan Agustin Di Pasquo 1 Dec 21, 2021
Example of integrating Poetry with Docker leveraging multi-stage builds.

Poetry managed Python FastAPI application with Docker multi-stage builds This repo serves as a minimal reference on setting up docker multi-stage buil

Michael Oliver 266 Dec 27, 2022
I'm curious if pydantic + fast api can be sensibly used with DDD + hex arch methodology

pydantic-ddd-exploration I'm curious if pydantic + fast api can be sensibly used with DDD + hex arch methodology Prerequisites nix direnv (nix-env -i

Olgierd Kasprowicz 2 Nov 17, 2021
FastAPI Admin Dashboard based on FastAPI and Tortoise ORM.

FastAPI ADMIN 中文文档 Introduction FastAPI-Admin is a admin dashboard based on fastapi and tortoise-orm. FastAPI-Admin provide crud feature out-of-the-bo

long2ice 1.6k Dec 31, 2022
A simple api written in python/fastapi that serves movies from a cassandra table.

A simple api written in python/fastapi that serves movies from a cassandra table. 1)clone the repo 2)rename sample_global_config_.py to global_config.

Sreeraj 1 Aug 26, 2021
row level security for FastAPI framework

Row Level Permissions for FastAPI While trying out the excellent FastApi framework there was one peace missing for me: an easy, declarative way to def

Holger Frey 315 Dec 25, 2022
A Nepali Dictionary API made using FastAPI.

Nepali Dictionary API A Nepali dictionary api created using Fast API and inspired from https://github.com/nirooj56/Nepdict. You can say this is just t

Nishant Sapkota 4 Mar 18, 2022
FastAPI Boilerplate

FastAPI Boilerplate Features SQlAlchemy session Custom user class Top-level dependency Dependencies for specific permissions Celery SQLAlchemy for asy

Hide 417 Jan 07, 2023
Backend logic implementation for realworld with awesome FastAPI

Backend logic implementation for realworld with awesome FastAPI

Nik 2.2k Jan 08, 2023