Assigning directory roles via the Graph API is possible, including to service principals. However the permissions required for that effectively give your app "the keys to the kingdom", so I doubt many organizations will be fine with granting them.
Here's the corresponding endpoint: https://learn.microsoft.com/en-us/graph/api/directoryrole-post-members?view=graph-rest-1.0&tabs=http