The attack on the popular Pearl Restaurant in a beach hotel happened early on Friday evening.
“Security forces have successfully neutralised the al-Shabab militants responsible for the terrorist attack on the Pearl Beach Hotel in Lido Beach, Mogadishu,” Somali National News Agency said on Twitter.
“A large number of civilians were rescued during the operation.”
The news agency posted photos showing soldiers in the restaurant responding.
One stood next to a glass door with a bullet hole in it, while sandals and a dustpan lay near him.
Hussein Mohamed, a waiter at another restaurant nearby, told Reuters he heard a blast followed by gunfire when the attack started.
“The whole area is cordoned off by security forces,” he said.
Abdikadir Abdirahman, the director of Aamin Ambulance Services, said they had so far received seven people who had been wounded.
Al Qaeda-linked al-Shabab said it was behind the attack.
“The Mujahideen managed to enter the Pearl Beach and are still fully in control,” the group said in a statement.
In November, the group, which controls swaths of the country, attacked another hotel in Mogadishu, killing nine.
Al-Shabab controlled a vast area of Somalia before being pushed back in government counteroffensives since last year.
However, the militants remain capable of launching significant attacks on government, commercial and military targets.
In late May, its fighters attacked a base housing Ugandan peacekeepers 130km southwest of Mogadishu, killing 54 soldiers.