Defending champion Barty was denied on five set-point chances in the final game of the first set before claiming it on a service winner after 37 minutes.
Former French Open champion Ostapenko broke 2019 Roland Garros champion Barty for a 2-0 lead to start the second set, but then surrendered the final six games, Barty looking much more impressive than she did in her three-set battle to subdue Kristina Kucova in her opening match.
"I was a lot sharper today," Barty said. "I felt like today was a lot cleaner. I felt like I really needed to be ready from the first ball."
Barty, who has spent 68 weeks atop the rankings, said she gained more confidence from her off-court work than her victories this week.
"I gain my confidence from all the work I do with my team," the Australian, who needed 50 hours to travel to Miami from Australia, said.
"We got here safely and I've been well prepared and now we're enjoying the sunshine."
Next up for Barty will be No.14 seed Victoria Azarenka from Belarus, who beat No.24 seed Angelique Kerber from Germany 7-5 6-2 in a battle of former world No.1s.
Azarenka, who was playing her first match after a first-round bye and a walkover, took a while to warm to the occasion.
But after trailing 4-1, she put the first set back on serve with a break in the seventh game and dominated from there, posting her ninth win in 10 meetings with Kerber.
While Barty cruised into the Round of 16, the women's draw lost world No.3 Simona Halep from Romania, who withdrew from her scheduled match with Latvian Anastasija Sevastova with a right shoulder injury.