The king's role in ancient Mesopotamia was to keep order in a world of many threats and in the context of an extremely pessimistic worldview. With constant dangers of floods and drought, kings had to protect the people in the realm, gather all the resources they could muster and honor the local gods whom the populace believed had the power to protect or destroy them.
Ancient Mesopotamia was a brutal place with an often unforgiving environment. The river systems constantly flooded, sometimes leaving people with no harvest at all. At other times, the river systems dried up, often with the same result. Therefore, preserving and distributing food stores and other resources properly was one of the chief duties of the king, and crimes that interfered with this were dealt with harshly.
Thus, the king was also a lawgiver, and he held his subjects accountable contractually to his decrees. The Code of Hammurabi, for example, is the oldest living document of this sort, and details many of the specific types of laws kings of the era may have implemented.
Finally, the king had to honor the deities that presided over his kingdom. This meant allowing the priests to do their work, as well as building and preserving temples. According to the Oriental Institute of the University of Chicago, Hammurabi in particular was obliged to “pay care and attention to the specific needs of the patron deities of the many cities incorporated into his realm.” Additionally, laws were believed to originate with the gods, so the king's function as lawgiver also contained a religious dimension. The gods of ancient Mesopotamia were rarely seen as benevolent, and were often depicted with horrible tempers. Thus, the king's actions were believed to be critical in appeasing them and for staving off natural disasters thought to be the result of the gods' displeasure.