A lengthy siege at Mogadishu's Ambassador Hotel ended early Thursday, said Somali security official Ahmed Barre.
One militant died in an initial car bomb attack, according to the National Intelligence and Security Agency.
Barre said the other two were killed by Somali special forces.
At least 40 other people were injured in the attack, according to Capt. Da'ud Hajji, a senior Somali police officer.
Two Somali lawmakers are among the dead, the Somali National News Agency reported.
The siege began when attackers detonated a car packed with explosives at the gates of the building, Hajji said.
The explosion shook nearby offices and injured bystanders in front of the hotel, witnesses said. Victims flooded a nearby hospital.
"Almost every 10 minutes they brought new people and bodies in," said Bashir Ali Mohamed, who was at the hospital visiting family members injured in the blast. "I have never seen such a horrible thing. Blood is everywhere."
More than two hours after the attack began, Mohamed said he could still hear gunshots and ambulances.
He felt the blast from his office a kilometer away, posting a photo on Twitter showing smoke rising in the distance.
Details are still emerging about the victims of the attack. Two members of Parliament, Mohamed Mohamud Gurre and Abdullahi Jama, were among them, the Somali news agency said.
The two lawmakers were close friends, a top Somali official said.
"Rarely saw them apart," Planning and International Cooperation Minister Abdi Aynte posted on Twitter. "Their bond was inseparable & they martyred together. RIP."
The Ambassador Hotel is a popular spot for Somali politicians and Westerners.
Authorities rescued 10 people and cleared out three of the hotel's four floors, according to the security agency. At least three of the people rescued were members of Somalia's Parliament, said Aden Osman, a hotel employee who also escaped the attack.
Al-Shabaab has used tactic before
Al-Shabaab claimed responsibility soon after the attack. Citing an unnamed commander, a statement on a website linked to Al-Shabaab said one of the group's jihadist fighters detonated a car with explosives at the gate, allowing armed militants to enter the building.
It's a tactic Al-Shabaab has used before, such as an attack at another hotel in the Somali capital
last year that left 15 people dead.
The militants aim to turn Somalia into a fundamentalist Islamic state.
The group has been blamed for attacks in Somalia that have killed international aid workers, journalists, civilian leaders and African Union peacekeepers.