FastAPI client generator

Overview

FastAPI-based API Client Generator

Generate a mypy- and IDE-friendly API client from an OpenAPI spec.

  • Sync and async interfaces are both available
  • Comes with support for the OAuth2.0 password flow
  • Easily extended, with built-in support for request middleware
  • Designed for integration with FastAPI, but should work with most OpenAPI specs
  • Makes use of https://github.com/OpenAPITools/openapi-generator

Look inside example/client to see an example of the generated output!


Warning: This is still in the proof-of-concept phase, and should not yet be considered to have a stable interface.

  • Some OpenAPI features (like discriminator fields) are not yet supported.
  • While the goal is to support any OpenAPI spec, it is most likely to work well with specs generated by FastAPI.

If you try this out, please help me by reporting any issues you notice!

Client library usage

from client.api_client import ApiClient, AsyncApis, SyncApis
from client.models import Pet

client = ApiClient(host="http://localhost")
sync_apis = SyncApis(client)
async_apis = AsyncApis(client)

pet_1 = sync_apis.pet_api.get_pet_by_id(pet_id=1)
assert isinstance(pet_1, Pet)

async def get_pet_2() -> Pet:
    pet_2 = await async_apis.pet_api.get_pet_by_id(pet_id=2)
    assert isinstance(pet_2, Pet)
    return pet_2

The example generated client library is contained in example/client.

Generated clients will have the following dependencies:

  • pydantic for models
  • httpx for networking
  • fastapi for jsonable_encoder and OAuth models (I hope to eventually remove this as a dependency)
  • typing_extensions for Enums via Literal (I eventually hope to replace this with standard enums)

More examples of usage (including auth) are contained in example/usage_example.py.

Generating the client library

Using the generator looks like

./scripts/generate.sh -i <openapi_json> -p <package_name> -o <output_path>
  [-n <import_name>] [--include-auth]
  [--] [*openapi-generator-args]

and will produce a client library at <output_path>/<package_name>.

The OpenAPI json input can be either a URL or a local file path.

For example, running

./scripts/generate.sh \
  -i https://petstore.swagger.io/v2/swagger.json \
  -p client \
  -o generated \
  -n example.client \
  --include-auth

produces the example client (along with the OAuth2.0 password flow client), places it in generated/client, and makes any generated client-referencing imports start with example.client.

(Note: to prevent accidental overwrites, you would need to manually remove generated/client if it already exists.)

With FastAPI

  • To generate a client for a default FastAPI app running on localhost (NOT inside a docker container):

      ./scripts/generate.sh -i http://localhost/openapi.json -p my_client -o generated
    
  • Since the generator runs inside docker, if your server is also running in a docker container on the same machine, you may need to provide a special hostname. Passing the --map-localhost argument will make the script attempt to perform this automatically:

      ./scripts/generate.sh --map-localhost -i http://localhost/openapi.json -p my_client -o generated
      # Transforms the input to http://host.docker.internal/openapi.json 
    

Generation details

  • The only local dependencies for generation are docker and standard command line tools.
  • openapi-generator is used to generate the code from the openapi spec
    • The custom templates are located in openapi-python-templates
  • autoflake, isort, and black are used to format the code after generation

Contributing

There are a variety of make rules for setup/testing; here are some highlights:

  • make develop: Sets up the local development environment.
  • make regenerate: Regenerates the example client from the example's openapi.json and the templates.
    • Note: This will overwrite changes! Make sure you commit (or edit the templates) before running this.
  • make: Checks that isort, black, flake8, mypy, and pytest all pass
  • make testcov: Generates a coverage report for the tests.

Pull requests are welcome and appreciated!

Owner
David Montague
David Montague
FastAPI + PeeWee = <3

FastAPIwee FastAPI + PeeWee = 3 Using Python = 3.6 🐍 Installation pip install FastAPIwee 🎉 Documentation Documentation can be found here: https://

16 Aug 30, 2022
A basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 273 Dec 01, 2022
A simple Redis Streams backed Chat app using Websockets, Asyncio and FastAPI/Starlette.

redis-streams-fastapi-chat A simple demo of Redis Streams backed Chat app using Websockets, Python Asyncio and FastAPI/Starlette. Requires Python vers

ludwig404 135 Dec 19, 2022
Cache-house - Caching tool for python, working with Redis single instance and Redis cluster mode

Caching tool for python, working with Redis single instance and Redis cluster mo

Tural 14 Jan 06, 2022
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Michael Freeborn 465 Jan 07, 2023
fastapi-cache is a tool to cache fastapi response and function result, with backends support redis and memcached.

fastapi-cache Introduction fastapi-cache is a tool to cache fastapi response and function result, with backends support redis, memcache, and dynamodb.

long2ice 551 Jan 08, 2023
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
OpenAPI for Todolist RESTful API

swagger-client OpenAPI for Todolist RESTful API This Python package is automatically generated by the Swagger Codegen project: API version: 1 Package

Iko Afianando 1 Dec 19, 2021
Twitter API monitor with fastAPI + MongoDB

Twitter API monitor with fastAPI + MongoDB You need to have a file .env with the following variables: DB_URL="mongodb+srv://mongodb_path" DB_URL2=

Leonardo Ferreira 3 Apr 08, 2022
Redis-based rate-limiting for FastAPI

Redis-based rate-limiting for FastAPI

Glib 6 Nov 14, 2022
FastAPI interesting concepts.

fastapi_related_stuffs FastAPI interesting concepts. FastAPI version :- 0.70 Python3 version :- 3.9.x Steps Test Django Like settings export FASTAPI_S

Mohd Mujtaba 3 Feb 06, 2022
FastAPI with Docker and Traefik

Dockerizing FastAPI with Postgres, Uvicorn, and Traefik Want to learn how to build this? Check out the post. Want to use this project? Development Bui

51 Jan 06, 2023
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 2022
REST API with FastAPI and PostgreSQL

REST API with FastAPI and PostgreSQL To have the same data in db: create table CLIENT_DATA (id SERIAL PRIMARY KEY, fullname VARCHAR(50) NOT NULL,email

Luis Quiñones Requelme 1 Nov 11, 2021
A comprehensive CRUD API generator for SQLALchemy.

FastAPI Quick CRUD Introduction Advantage Constraint Getting started Installation Usage Design Path Parameter Query Parameter Request Body Upsert Intr

192 Jan 06, 2023
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://fastapi-users.github.io/fastapi-users/ Source Code: ht

FastAPI Users 2.3k Dec 30, 2022
Easily integrate socket.io with your FastAPI app 🚀

fastapi-socketio Easly integrate socket.io with your FastAPI app. Installation Install this plugin using pip: $ pip install fastapi-socketio Usage To

Srdjan Stankovic 210 Dec 23, 2022
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

Laurent Savaete 562 Jan 01, 2023
A RESTful API for creating and monitoring resource components of a hypothetical build system. Built with FastAPI and pydantic. Complete with testing and CI.

diskspace-monitor-CRUD Background The build system is part of a large environment with a multitude of different components. Many of the components hav

Nick Hopewell 67 Dec 14, 2022
A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication and Rate Limits

A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication and Rate Limits Install You can install this Library with: pip instal

Tert0 33 Nov 28, 2022