Article: Context.APIException - User context must first be passed to setUserContext

Tags: #<Tag:0x00007f828d7cc6c8> #<Tag:0x00007f828d7cc470>

Hello Everyone,

I have come to realise that there is a popular error developers have been facing while hacking OpenMRS which is:

org.openmrs.api.Context.APIException: A user context must first be passed to setUserContext()…use Context.openSession() and (closeSession() to prevent memory leaks!) before using the API."

I want to write a Blog Article on this problem ie: possible causes and solutions to each case. @michael suggested I could use gist on github for this. I am currently exploring the threads on this error and any suggestions from the Developer community and possible causes and solutions will be greatly appreciated. I’ll publish the link to the Blog post to the community once I’ve taken everyone’s suggestions.

Cheers! Nyah


Dear @ch3ck

I am facing this issue now. I am tying to use spring componentscan in the radiology modules moduleApplicationContext. It instantiates a bean of a class annotated with spring’s @component. The error occurs when I call a method on a member that is autowired. Some member of this member seems to need the OpenMRS api context.

Do you have any suggestions?

Hello @teleivo

This problem is very common and usually depends on the context. I think this thread discusses most of it: Context API Exception issue. This is the best reference I have seen on this error; hope it helps.

Cheers! Nyah


I also see this error on my openmrs test system for any bad url, ie going to http://localhost:8080/openmrs/thisisabadurl

Maybe this is an issue with my test deployment?