According to this Reddit thread (which was linked in a comment by Hentold, but seems to have been ignored otherwise... I found that thread and this question when trying to figure this out), happiness has a number of factors. Some of the other answers on this question do not have the correct factors, though.
First off, settlement happiness is an average value computed from each individual settler's happiness. Humans can have a happiness between 0 and 80, while non-humans have their happiness set to 50.
Humans' happiness is a factor of:
- A place to sleep (under a roof)
- 1 food to eat
- 1 water to drink
- A safety value greater than the number of settlers
Not meeting these basic requirements causes very low happiness for an individual settler.
Once all the settlers' individual happiness numbers are computed, a bonus is added to the total before dividing to get the average. This bonus can be influenced by:
- The junkyard dog (or other pets, gorillas and cats with the DLC)
- Stores (+8 to +40, depending on type and size, Large Bar being the best)
Once the average is computed, modifiers are applied. The influences here are settlement quests and settler deaths. This modifier decays towards 0 at a rate of 20% per day. If you bork up a quest or someone dies, happiness will take a dive but then eventually bounce back.
The computed happiness value doesn't take effect immediately, however. changes between current and computed happiness take place over the course of several days. So, if you mass build a bunch of things that ought to impact happiness in a settlement, it will take time for it to reach the new equilibrium.