The gunmen had approached the restaurant from Lido beach on Thursday evening, firing on diners.
Twenty people were killed. Militants also detonated two car bombs nearby.
Al-Shabab said it was behind the attack. The group has carried out frequent assaults on the Somali capital.
Troops then besieged the attackers at the restaurant for eight hours. It was not immediately clear how many of the militants were killed or captured.
The Somali authorities said the leader of the attack had been arrested.
Prime Minister Omar Abdirashid Ali Sharmarke condemned the killings as "barbaric".
There are varying reports about how the attack started but it appears that as the first car bomb went off, at around 19:30 local time (16:30 GMT) on Thursday, the gunmen stormed the area.
"They randomly fired at the people sitting near the beach before entering the restaurant,'' witness Ahmed Nur told Associated Press.
Twenty people were injured in addition to those killed, police said.
Lido beach, on the northern edge of Mogadishu, attracts thousands of mostly young Somalis who come to relax and enjoy the beach and the surf.
Several restaurants have opened up along the beach front in recent years, and people would have been sitting out in front of them when the attacks began.
Al-Shabab, which has links to al-Qaeda, was ousted from Mogadishu in August 2011, but still has a presence in large areas of southern Somalia.
The group stormed an African Union military base last week in southern Somalia, killing dozens of Kenyan troops.
At least 235 people were killed and another 109 injured in an attack on a Sufi mosque in Egypt's North Sinai region on Friday, Egyptian state-run media reported, in what appears to be the deadliest terror attack on Egyptian soil.
3 years, 5 months ago