The story and history of Lord Hanuman goes back thousands of years, at the time of Ramayana. There are multiple legends of how He took birth, and the following are some of them:
King Dasharatha was performing the Putrakameshti yajna, Yajna or puja to help him get his heirs as he was childless. After the end of his successful yajna, a payasam emerged from the yajna fire, which was required to be consumed by his queens to bear kids. At that very moment, a kite (a bird of prey) snatched some of that that holy payasam and flew up. Vayu or Pawan dev, lord of the air and wind, retrieved it from the kite, and gave it to Anjana, an apsara, who ate it. Thereafter, hanuman was born of Anjana, and was known as Pawan Putra, or son of Vayu.
He is also called to be an avatar or reincarnation of Rudra, the most powerful form of Lord Shiva.
As per another legend, there was an apsara by the name of Punjikasthal in the heavens at Lord Indra’s court. Once a great sage by the name of Angira went to the heavens to visit Indra. To please him, Indra asked Punjikasthal to perform a dance only for the sage. Punjikasthal tried her best, but the sage was not interested in her dance, and went into meditation. Since she disappointed the sage, the sage cursed her that she will be born as a monkey on earth.
She reverently asked for forgiveness from the saint. Impressed, the saint told her that she will give birth to a gret devotee of Lord. Your son will forever serve the Lord.
She took birth as the daughter of Kunjar (king of the monkeys) and got married to Kapiraj Kesari of the Mount Sumeru. She prayed deeply to Lord Shiva and urged Him to be a part of her son who was yet to be born. The Lord listened to Kesari and took birth from her, in the form of Hanuman.
It is believed that Lord Shiva took the birth of Hanuman to serve Lord Vishnu in His Ram avatar, as he could not do it without taking a birth at the earth.