Walter Mazzarri's side struggled to impress and, after hitting the post early on, the Partenopei spent most of the time defending.
Cagliari hit the woodwork twice and looked more likely to score until Hamsik pounced on a loose ball to earn the visitors all three points and take them above Inter Milan and Fiorentina.
Lorenzo Insigne rattled the post at the end of a rare Napoli attack in the 21st minute, but Cagliari were largely the livelier of the two teams in the first half.
A good cross-field ball to Thiago Ribeiro set him up for a good chance in the 31st minute, but he could not keep up with the pace and his shot was weak and off target.
At the other end, Blerim Dzemaili picked out Insigne with a long, searching ball and he cut back inside a defender but shot wide of the near post.
Alessandro Gamberini almost gave Napoli the lead when he diverted a corner against his own post, before Danilo Avelar tried a speculative lob from 35 yards which landed on the roof of the net after De Sanctis had left his goal vacant.
Cagliari started the second half brightly with Radja Nainggolan cutting in from the left, but his shot was straight at De Sanctis from a tight angle
Paolo Cannavaro was the next Napoli player to almost put through his own goal in the 48th minute with the ball hitting the top of the crossbar before Nainggolan volleyed wide.
A goalmouth scramble saw Michael Agazzi called into action twice on the hour mark before Hamsik put Napoli ahead with a rare attack in the 72nd minute.
Juan Zuniga put pressure on Albin Ekdal, who nudged the ball inadvertently to Hamsik to curl into the far corner from eight yards.
It was harsh on Cagliari, who tried to find an equaliser, but the Rossoblu were unable to find one.