Bagnaia edges out Bastianini to win San Marino GP
Ducati's Bagnaia finished 0.034 seconds ahead of Gresini Racing rider Bastianini as he celebrated a thrilling victory after starting fifth on the grid.
He became the first Ducati rider to win four consecutive MotoGP races, having also triumphed in the Austrian, British and Dutch Grand Prixs.
Bagnaia closed the gap on world championship leader Fabio Quartararo of Yamaha to 30 points.
Maverick Vinales (27) of Aprilia Racing completed the podium and Quartararo finished fifth after starting eighth on the grid following a disappointing qualifying session.
Pole sitter Jack Miller crashed out of the lead on the opening lap and ended the race in 18th on his Ducati. Mooney VR46 Racing Team's Marco Bezzecchi also crashed and finished 17th after starting third.
Italian Andrea Dovizioso came 12th for the Yamaha RNF team in his final race in the premier class.