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.