The 27-year-old European champion hung tough as a group of five Chinese walkers, led by Wang, tried to stretch the pace from the start but the group splintered under the strain and Lopez had enough stamina to hit the front in the closing stages.
He passed Wang at the 18-km mark and pumped his fist in delight as he crossed the line in a personal best time of one hour 19 minutes 14 seconds, 15 seconds ahead of the Chinese, to become the first Spanish winner since Valenti Massana in 1993.
“This is the best moment of my life,” Lopez told reporters. “The course was complicated plus the heat. It was a tactical race but I kept my calm. My last 200 (metres) was an incredible sensation.
“I hoped the people of Spain watched me at three in the morning. They should see this unique moment of my life.”
Wang, 23, bronze medallist at the London Olympics three years ago, refused to be disappointed at his near miss.
He and a quartet of team mates had controlled the early fast pace but he opted to make a solo break at the 13-km mark, opening up a sizeable lead that looked to be enough for gold.
But a steely Lopez closed the gap at the 17km mark before overtaking an exhausted and grimacing Wang shortly after, powering home to the Bird’s Nest with the Chinese athlete unable to match the pace.
“It became tough toward the end as the race started to get rushed,” Wang said.
“I was not nervous but I felt some pressure as this competition takes place in China.”
Canada’s Ben Thorne took bronze, 43 seconds behind Lopez, while Ukraine’s Igor Glavan was fourth in a season’s best time of 1.20:29.
Cai Zelin, who had been part of the early Chinese front running group, was fifth despite stopping at the three quarter mark clutching his stomach and looking close to vomiting.
Olympic champion Ding Chen, another of the Chinese pace-setters, had to settle for ninth.
World record holder Yusuke Suzuki of Japan quit just after halfway through in ever-increasing heat in the Chinese capital.
(Writing by Patrick Johnston in Singapore; Editing by Ian Ransom)