Farmajo was declared victorious after incumbent President Hassan Sheikh Mohamud dropped out of the contest following the second round of voting.
Amid rising security concerns, the 328 members of Parliament met at an air force hangar in Mogadishu to cast their votes.
Mohamud, who took office in 2012
, withdrew from the final ballot after losing 184 to 97 to Farmajo in the second round.
Farmajo's victory was greeted by celebratory gunfire in government-controlled areas of the country.
Lived in Buffalo
Farmajo, 54, was born in Mogadishu. He worked at the Somali Embassy in Washington in the mid-1980s and decided to stay in the United States because of political turmoil in Somalia, according to his campaign website biography.
He moved to Buffalo, New York, because of its sizable community of Somali refugees, reported the Buffalo News
, citing his daughter, Intisar Mohamed, who still lives in the area.
He worked as Buffalo Municipal Housing Authority commissioner and at the New York State Department of Transportation, the campaign website said. He earned a bachelor's and master's degrees from the State University of New York (SUNY) at Buffalo, the website said.
In 2010 then-President Sheikh Sharif Ahmed asked him to serve as prime minister, a position he resigned because of a rift with the President, the Buffalo News reported.
"Somalia moving forward towards progress," tweeted the nation's minister of foreign affairs, Abdusalam H. Omer, in reaction to Farmajo's win.
Terror and famine
Farmajo faces many challenges in governing Somalia, one of the seven Muslim majority countries that President Donald Trump included in his executive order on immigration.
The order currently is under challenge in the US courts.
One of the world's poorest countries, Somalia's
governance structure, economic infrastructure, and institutions have been destroyed by civil war, the World Bank reports.
Extremist groups such as Al-Shabaab emerged early this decade and have staged brazen attacks throughout the nation.