Alex
Alex

Reputation: 51

Can I create a service in fastapi using an imported function from another .py file?

I have written some functions with python in separate files. My task is to transform these functions into services using fastAPI and the services should return a JSON that says if the operation is executed correctly or not (a code and a message).

For example, I have a file sum.py and inside there's a function that sums two numbers and returns the result:

def sum_of_two_numbers(a,b):
    tot = a+b
    return tot

Let's say I want to create a service using fastAPI, do you know if I can import sum_of_two_numbers from sum and use TestClient to complete this task without modyfing the code or re-writing it?

In this example the function is short, but have in mind my functions are different. I needed one month to write them all and make the connection to the Oracle db. While reading the documentation of fastAPI, I understood I should modify all the syntax to adapt it for fastAPI.

So, in short can I do this with fastAPI by simply importing the functions and without changing all the functions syntax? Or do you know if is there an easier way to do it?

Upvotes: 0

Views: 2571

Answers (1)

Bastien B
Bastien B

Reputation: 1323

In a basic fastapi app structure you often have something like this:

Example taken from Bastien-BO/fastapi-RBAC-microservice, inspired by Kludex/fastapi-microservices and tiangolo/full-stack-fastapi-postgresql

.
├── app
│   ├── __init__.py
│   ├── main.py
│   ├── dependencies.py
│   └── routers
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   └── models
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   └── schemas
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   └── internal
│   │   ├── __init__.py
│   │   └── crud
|   |   |   └── user.py
|   |   |   └── item.py

Often in your internal files you have functions or classes that you can serve with routes.

Example of a user route with internal db function call:

# app/routers/users.py
from app.internal.crud.user import crud_user

@router.get("/", response_model=List[UserOut])
async def read_users(offset: int = 0, limit: int = 100, session: Session = Depends(get_db)):
    users = crud_user.get_multi(session, offset=offset, limit=limit)
    return users
# app/internal/crud/user.py

def crud_user():
    #do db stuff here

In this example, your sum_of_two_numbers function would be in the internal folder and you would wrap it in a route like what is done in read_users.

You should follow the user guide or the advanced user guide (fit better to your need i believe) from fastapi official doc. Also take a look at tiangolo (fastapi creator) Base Project Generator. You will have a good example on how to create a strong base for your API.

Upvotes: 2

Related Questions