Endorphin's are morphine like chemicals, your body's own stash of opiates that help decrease pain and create feelings of euphoria. A legal drug that is produced within your own body. From an evolutionary perspective it would seem that endorphins role is to allow us to persist despite some stressor.
The pituitary gland releases endorphins in response to stress, and that could be strenuous exercise, emotional stress, pain, and even under nourishment i.e.dieting.
Endorphins work to relieve pain and also induce euphoria, which leads to it playing a role in your brain's reward system. In exercisers this is the well known phenomenon "runner's high," which relates to the highs experienced post exercise, and the serious lows if they can't fit in that run or gym session.
From a clinical perspective these "feel-good" chemicals play a role in addiction to exercise and dieting, in which an individual habitually returns to starvation/fasting protocols despite poor previous results. When they discontinue a diet or can't train the stressor is removed and the endorphins are no longer released, leaving the individual with symptoms such as anxiety, pain, depression, guilt etc. Only when the stressor returns does the exerciser/dieter get their fix of opiate-like chemicals.