Lets assume "creating or getting sessions inside the function" is the way at start.
For any real world API, get_user_by_id
is not going to be the only method is it?
There are likely to exist similar methods: get_posts_by_user(post_id)
, get_comments_for_post(user_id)
, like_post(post_id)
and so on.
Would it make sense to duplicate session creation code everywhere ?
Obviously not. Lets suppose we extract the common logic regarding creation or retrieval of a, DB or Authentication, session in session_provider.get_session()
.
How are all the API methods going to get session_provider
in the first place ?
Well, it can be saved in globally accessible state or even can be a singleton. It is general consensus that both global state and singletons are best avoided.
The remaining option is to pass the session_provider
from outside (by whomever that wants to call the API methods.) Also known as providing dependencies externally.
Lets suppose the session_provider
is passed to the constructor of API class having all these methods:
class api {
constructor(session_provider){...}
get_user_by_id(user_id){
session = this.session_provider.get_session();
...
}
}
So far so great. Now let's focus how other code uses the API. Suppose a request handling function:
handle_get_user_request(http_request){
provider = new session_provider();
api = new api(provider);
user_id = http_request.get_param('id');
return api.get_user_by_id(user_id);
}
Are not we doing the same mistake again ? Creating the dependencies of a function inside it!
Considering we fully embrace the "providing dependencies externally" concept, we would have code where, the things required to compute something, are passed to the function doing the computation:
handle_get_user_request(http_request, api, session){
user_id = http_request.get_param('id');
return api.get_user_by_id(session, user_id);
}
Here we are, with get_user_by_id(session, user_id)
version of the function. Welcome to Dependency Injection.
session
in this context? From your code, I'm guessing it might be something Pythonic, but even so you need to tell us which DB access library you're using.