A large blast hit an area near Mogadishu airport hours later, residents said.
It was not immediately clear who carried out the attacks, but al-Shabaab militants linked to al-Qaeda have claimed responsibility for a number of suicide bombings in Mogadishu this year.
"About seven well-armed men in government uniform entered the court today as soon as a car bomb exploded at the gate. We thought they were government soldiers," said Aden Sabdow, who works at the mayor's office adjacent to the court.
"There are many government officials inside the court which has been busy these days," he said.
"Armed men entered the court and then we heard a blast. Then they started opening fire. We do not know the number of casualties," said Hussein Ali, who works at the courts.
Somali forces arrived and besieged the court compound and there was a second blast while shots continued to ring out.
Reuters reporters counted 16 bodies, some of them in uniform, some not, around the compound, but it was not clear how many of them were government soldiers, attackers, or civilians.
Later, a car bomb exploded at a building housing Somali intelligence along the road to the airport as Turkish and African Union (AU) vehicles were passing, police and witnesses said. Government forces then opened fire and blocked the road.
"The car bomb exploded near the gate of a building housing the Somali security. AU and Turkish cars were also passing there. We are still investigating the target and casualties," Qadar Ali, a police officer told Reuters.
Britain warned on April 5 it believed "terrorists are in the final stages of planning attacks in Mogadishu".
In control of much of the capital Mogadishu between 2009 and 2011, al-Shabaab has been forced out of most major cities in central and southern Somalia by African Union peacekeepers.
But the hardline Islamist group has hit back with a series of bomb attacks. In early April, a bomb went off outside the headquarters of Somalia's biggest bank, Dahabshiil's, wounding at least two people hours after al Shabaab ordered the company to cease operations in areas under its control.
Last month, al-Shabaab claimed responsibility for suicide car bomb targeting a senior Somali security official which killed at least 10 people in central Mogadishu. The security official survived the attack, the city's deadliest this year. – Reuters