Mohamed Abdullahi Farmajo immediately took the oath of office as the country moved towards its first fully functioning central government in a quarter of a century.
Incumbent president Hassan Sheikh Mohamud conceded defeat after two rounds of voting, and Mr Farmajo was declared the new leader.
“History was made, we have taken this path to democracy, and now I want to congratulate Mohamed Abdullahi Farmajo,” Mr Mohamud said.
The election took place under heavy security amid threats from the extremist group al-Shabaab, with a security lockdown leading to the closure of the capital’s international airport and clearing major streets.
Mr Mohamud held a slight lead over Mr Farmajo, 88 votes to 72, after the first round of 21 candidates, but Mr Farmajo held a clear lead after the second round among the three candidates remaining.
Celebratory gunfire rang out in the capital, Mogadishu, from soldiers supporting Mr Farmajo, police said.
“This victory represents the interest of the Somali people. This victory belongs to Somali people, and this is the beginning of the era of the unity, the democracy of Somalia and the beginning of the fight against corruption,” Mr Farmajo said after taking the oath.
Years of warlord-led conflict and al-Shabaab attacks, along with famine, have left the Horn of Africa country of about 12 million people largely shattered.
Members of the upper and lower houses of the legislature dropped their ballots into clear boxes at the heavily guarded election venue, a former air force base in Mogadishu.
Fears of al-Shabaab attacks limited the election to politicians instead of the population at large.
Across Mogadishu, Somalis gathered around TV screens at cafes and homes, eagerly watching the vote.
“I hope they will not choose bribes over the interest of the people,” said Ahmed Hassan, a 26-year-old university student, who sat with dozens of men in front of a large television screen.
“We need an honest leader who can help us move forward.”
Somalia’s instability landed it among the seven Muslim-majority countries affected by US president Donald Trump’s executive order on immigration.