From Yamaha Fabio Quartararo retained the world championship lead despite finishing in eighth place.
This was Bagnaia’s debut success in the premier class after a combined 10 victories in Moto2 and Moto3.
After taking pole position with a record time on the track on Saturday, Bagnaia led from the start followed by Márquez, who was seeking his 58th MotoGP victory.
The pair soon broke away from the group with Marquez launching multiple attacks in the closing laps.
On his last pass attempt, the Spaniard, who was born not far from the Motorland circuit, veered too far around a corner, allowing Bagnaia to make a hard-fought but well-deserved first MotoGP victory.
“This victory today is like a liberation. We have worked hard to obtain this result,” Bagnaia said.
Defending world champion Joan Mir came third.
With five rounds of the season to go, Quartararo leads the race for the drivers’ crown with 214 points, with Bagnaia in second place with 161 and Mir four more points adrift.
Bagnaia led from pole with his official Marquez Ducati and Australian Jack Miller on the other Ducati.
Quartararo, who started in the front row, got off to a bad start, falling back to seventh.
Marquez kept pace with Bagnaia with the front pair pulling more than three seconds away from the chasing group now led by Mir as Miller slid into fifth place with a dozen laps to go under the Spanish sun.
This track has never been kind to Quartararo and the 22-year-old was unwilling to change that trend as he approached the final laps in ninth place.
Marquez was getting closer and closer to Bagnaia, ready to jump.
With three laps to go he tested the temperature, climbing inside to briefly take the lead.
He tried again and again, but each time Bagnaia had him covered until Márquez lost ground by opening up more on the last lap.
Bagnaia’s compatriot Dennis Foggia took Moto3 honors earlier when Spanish duo Pedro Acosta and Sergio Garcia, the top two in the championship standings, fell.
Local fans had a winner at home to celebrate with Raúl Fernández beating Australian Remy Gardner to win the Moto2 race.