-1

Currently I'm working on FastAPI endpoints in Python which basically handle two types of entities:

/run/entityA
/run/entityB

Now based on the type of entity, some of the arguments change but a lot of the processing of other arguments overlap.

Current approach:

@router.post("/run/entityA")
def _run_a(args_a):
    # Common processing
    # Entity A related processing
    # Common processing

@router.post("/run/entityB")
def _run_a(args_b):
    # Common processing
    # Entity B related processing
    # Common processing

Previous Approach

Previously, I kept one set of args, keeping the entity related args as Optional in FastAPI and doing an if check inside the function:

@router.post("/run")
def _run(args):
   # Common Processing
   if args.entityA_arg:
   # Entity A related processing
   if args.entityB_arg:
   # Entity B related processing
   # Common processing

I see downsides in both. What are some suggestions to make the code cleaner?

2
  • 1
    maybe common processing put in separate function and execute it in /run/entityA and /run/entityB Commented Feb 25 at 4:49
  • @Shubham give a path parameter answer, which is greate, and for your information in FastAPI the order of path operation is matter Commented Feb 25 at 14:12

1 Answer 1

1
@router.post("/run/{entity}") 
def _run_(entity:str):
 if entity = a: 
  #for a
 else:
  #for b

You can try this beautiful way.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.