Skip to main content

FastAPI Microservice Helper

Introduction

FastAPI Microservice Helper is an SDK designed to facilitate communication between microservices over HTTP.

  • It automatically generates the necessary code to build services and can be installed in client applications.
  • It automatically mocks the response from the server if you're writing e2e tests.

How to use

Let's say we have a CoreMicroservice that handles creating and retrieving posts. Now, we want to call this CoreMicroservice from a UserMicroservice.

Step 0: Config Microservice

In DEV env, swaggers will show the api endpoints, and in PROD env, the api endpoints will be hidden

# config/microservice.py
from fastapi_microservice_helper import FastApiMicroservice

FastApiMicroservice.config(env='DEV')

Step 1: Define Microservice Actions on the Server

In the CoreMicroservice, you define actions for handling posts. Here's an example:

# http/microservices/post.py
from uuid import UUID

from fastapi import Depends, Query
from fastapi_microservice_helper import action, microservice
from fastapi_request_helper.decorators.http_method import response, tag

from posts.http.responses.general_post_response import GeneralPostResponse
from posts.services.post import PostService

class GeneralPostResponse(BaseModel):
  id: UUID
  author_id: UUID

class CreatePostDto(BaseDto):
  author_id: UUID

@microservice()
@tag('Microservices Post')
class PostMicroservice:
  def __init__(self, post_service: PostService = Depends()):
    self.post_service = post_service

  @action()
  @response(GeneralPostResponse)
  async def get_post(self, post_id: UUID):
    return await self.post_service.find_general_post_by_id(post_id)

  @action()
  async def create_post(self, dto: CreatePostDto):
    await self.post_service.increment_post_likes(dto)

In this example, we define two actions for PostMicroservice:

get_post to retrieve a post by ID create_post to create a new post.

Step 2: Step 2: SDK Generation

FastAPI Microservice Helper automatically generates the SDK code based on the server definitions. Here’s an example of what the generated client SDK might look like:

# sdk/src/core_microservice/sdk.py
...

class BaseMicroserviceClient:
  def filter_none_values(self, query_params: dict | None):
    return {key: value for key, value in query_params.items() if value is not None} if query_params else None

  async def send(
    self, url: str, query_params: dict, body_params: any, response_type: any, option: MicroserviceOption = None
  ):
    if not CoreMicroserviceConfig.url:
      raise Exception('Please config microservice url')

    url = CoreMicroserviceConfig.url + url
    if not option:
      option = MicroserviceOption()

    async with httpx.AsyncClient() as client:
      response = await client.post(
        url=url,
        headers=option.headers,
        params=self.filter_none_values(query_params),
        data=body_params if not option.is_json else None,
        json=Normailization.normalize(body_params) if option.is_json else None,
      )
      data = response.json()
      if response.status_code < 200 or response.status_code > 299:
        raise HTTPException(status_code=response.status_code, detail=data)
      if not response_type:
        return data

      return TypeAdapter(response_type).validate_python(data)

class PostMicroservice(BaseMicroserviceClient):
    async def decrement_post_likes(self, dto: DecrementPostLikesDto , option: MicroserviceOption = None) -> None:
        return await self.send('/microservices/PostMicroservice/decrement_post_likes', None, dto, None, option )
    
    async def get_post(self, post_id: UUID , option: MicroserviceOption = None) -> GeneralPostResponse:
        return await self.send('/microservices/PostMicroservice/get_post', {'post_id': post_id}, None, GeneralPostResponse, option)

    async def create_post(self, dto: CreatePostDto , option: MicroserviceOption = None) -> None:
        return await self.send('/microservices/PostMicroservice/create_post', None, dto, None, option)

Step 3: Build and Publish the SDK

Increase the version in sdk.toml file then build and publish it, for example, publish the sdk as core-microservice==0.0.1.

Step 4: Configure the Microservice in the Client

Install the SDK

Add the SDK to your project’s dependencies in requirements.txt:

# requirements.txt
core-microservice==0.0.1

Then install the required packages:

pip install -r requirements.txt

Configure the Microservice URL

Set the base URL for the CoreMicroservice:

# config/microservice.py
from core_microservice import CoreMicroserviceConfig
CoreMicroserviceConfig.url = 'http://127.0.0.1:8000'

Step 5: Use the Microservice in Client Code

In the UserMicroservice, you can now use the SDK to call actions from CoreMicroservice:

# services/user.py
class UserService:
    def __init__(self, post_microservice: PostMicroservice = Depends()):
        self.post_microservice = post_microservice

    async def create_post(self, dto: CreatePostDto):
        await self.post_microservice.create_post(dto)

    async def get_post(self, post_id: UUID):
        return await self.post_microservice.get_post(post_id)

Metadata

Release files for fastapi-microservice-helper 0.0.42

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

Source distribution (sdist)

Source distribution for fastapi-microservice-helper 0.0.42
File Size Uploaded Provenance Actions
fastapi_microservice_helper-0.0.42.tar.gz 12.7 kB Without provenance Details for fastapi_microservice_helper-0.0.42.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-microservice-helper 0.0.42
File Interpreter ABI Platform Actions
fastapi_microservice_helper-0.0.42-py3-none-any.whl Python 3 none any Details for fastapi_microservice_helper-0.0.42-py3-none-any.whl

Total release size: 25.8 kB

Release files / fastapi_microservice_helper-0.0.42.tar.gz

Download URL fastapi_microservice_helper-0.0.42.tar.gz
Size 12.7 kB
Tags Source
SHA-256 checksum
How to use checksums
a249941eca682e1f9b91ae032692f66703c1370dc5788f5d5c6bddf78e79eef6
BLAKE2b-256 checksum
How to use checksums
7f39ac83db54385719589e31f1c040b5b4dc8677b8413dbd3c9ee2a4b7189a80
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.16

Release files / fastapi_microservice_helper-0.0.42-py3-none-any.whl

Download URL fastapi_microservice_helper-0.0.42-py3-none-any.whl
Size 13.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e13962e6b7ce63dc4094157673c281a376e43fb01035c2e0fbc766eb0eba90d8
BLAKE2b-256 checksum
How to use checksums
254ee2234b1fcee3fb8de02c5a0a9d69279e87162c4d570248137d7168726083
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.16

Security for fastapi-microservice-helper 0.0.42

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.0.42 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