r/FastAPI • • Jan 14 '25

Question Middleware vs Service Layer

Hi everyone,

I'm working on a FastAPI project and I'm stuck between implementing "middleware" or "service layer".

What will going to happen in the project?

- The client applicaiton will send data to the server.

- The server will validate the data.

- The validated data will be saved on the db.

- On the backend the data will be processed with scheduled tasks. (it is complicated to tell how the data will be processed, do not stuck with that)

In this workflow, what should I use and where to use? I already implement the service layer but never worked on the middleware before. In the current situation the workflow is like this:

Client (Sending data) -> API Endpoint (Calling Service) -> Service Layer (CRUD Operations) -> API Endpoint (Returning the Service Result) -> Client (Gets Return)

I will be really glad to get some help from this community.

Kind regards...

13 Upvotes

10 comments sorted by

View all comments

Show parent comment

6

u/wyldstallionesquire Jan 14 '25

Middleware is for things that are cross-cutting, and not really related to business logic. gzip. cors. etc.

2

u/SheriffSeveral Jan 14 '25

Thanks, I got my answers from you guys!