Often the UI code gives clues
Turn on developer extras in user preferences and can right click and view source of most UI elements.
Do this over toggle xray button and It takes us to the draw code, in text editor, of the operator button in 3d view.
"show_xray_wireframe" if shading.type == 'WIREFRAME' else
Trecking up we see
shading is a pointer property of the
SpaceView3d This is
context.space_data in the 3d view, but not in text editor or console. A reason for the failed context error.
-- remnder: post like to codemanx's override context answer, or easier still See Merlin's answer --
We could simply find the area and space and other required members and pass as an override dictionary to the operator, however we may be able to simply toggle a property of the space.. much easier.. off to the python console to investigate
get all the 3d view areas in the context screen
>>> views3d = [a for a in C.screen.areas if a.type == 'VIEW_3D']
iterate over them and see what the values are using code above as clue. The space from an area is
>>> for a in views3d:
... shading = a.spaces.active.shading
Hmm ok let's see
>>> shading.show_xray = False
and bingo, toggles shading. I'll leave you to decide on how to handle
show_xray_wireframe based on