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
This project is a realworld backend based on fastapi+mongodb

This project is a realworld backend based on fastapi+mongodb. It can be used as a sample backend or a sample fastapi project with mongodb.

邱承 381 Dec 29, 2022
FastAPI Skeleton App to serve machine learning models production-ready.

FastAPI Model Server Skeleton Serving machine learning models production-ready, fast, easy and secure powered by the great FastAPI by Sebastián Ramíre

268 Jan 01, 2023
volunteer-database

This is the official CSM (Crowd source medical) database The What Now? We created this in light of the COVID-19 pandemic to allow volunteers to work t

32 Jun 21, 2022
Online Repo Browser

MSYS2 Web Interface A simple web interface for browsing the MSYS2 repos. Rebuild CSS/JS (optional): cd frontend npm install npm run build Run for Dev

MSYS2 64 Dec 30, 2022
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

Ahmed BESBES 60 Dec 17, 2022
signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests

signal-cli-rest-api signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests. Features register/ver

Sebastian Noel Lübke 31 Dec 09, 2022
Web Inventory tool, takes screenshots of webpages using Pyppeteer (headless Chrome/Chromium) and provides some extra bells & whistles to make life easier.

WitnessMe WitnessMe is primarily a Web Inventory tool inspired by Eyewitness, its also written to be extensible allowing you to create custom function

byt3bl33d3r 648 Jan 05, 2023
Auth for use with FastAPI

FastAPI Auth Pluggable auth for use with FastAPI Supports OAuth2 Password Flow Uses JWT access and refresh tokens 100% mypy and test coverage Supports

David Montague 95 Jan 02, 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
Analytics service that is part of iter8. Robust analytics and control to unleash cloud-native continuous experimentation.

iter8-analytics iter8 enables statistically robust continuous experimentation of microservices in your CI/CD pipelines. For in-depth information about

16 Oct 14, 2021
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
An extension for GINO to support Starlette server.

gino-starlette Introduction An extension for GINO to support starlette server. Usage The common usage looks like this: from starlette.applications imp

GINO Community 75 Dec 08, 2022
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

Bobynets Ivan 1 Oct 29, 2021
A Python pickling decompiler and static analyzer

Fickling Fickling is a decompiler, static analyzer, and bytecode rewriter for Python pickle object serializations. Pickled Python objects are in fact

Trail of Bits 162 Dec 13, 2022
FastAPI Learning Example,对应中文视频学习教程:https://space.bilibili.com/396891097

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

381 Dec 11, 2022
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
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

Cloud Bytes Collection 1 Nov 24, 2022
Code for my JWT auth for FastAPI tutorial

FastAPI tutorial Code for my video tutorial FastAPI tutorial What is FastAPI? FastAPI is a high-performant REST API framework for Python. It's built o

José Haro Peralta 8 Dec 16, 2022
FastAPI构建的API服务

使用FastAPI 构建的商城项目API 学习FastAPI 构建项目目录 构建项目接口: 对应博客:https://www.charmcode.cn/article/2020-06-08_vue_mall_api 声明 此项目已经不再维护, 可以参考我另外一个项目https://github.co

王小右 64 Oct 04, 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