The Americans defended their title from four years ago in Beijing, also against Spain.
"This game was fun. It was a challenge, but we stepped up to it," Kobe Bryant told NBC, an official broadcaster of the Games.
LeBron James had 19 points and Bryant scored 17 for the Americans, who led by only one point after the third quarter.
"We all respect each other," Durant said. "We all know it's our common goal."
Russia narrowly edged out Argentina for the bronze.
London itself took center stage on the last day of the Olympics on Sunday, with the men's marathon course running past the city's major landmarks from Big Ben to Buckingham Palace.
Kiprotich won a thrilling race in 2:08:01, dueling for miles with early leader Wilson Kipsang of Kenya and his compatriot Abel Kirui.
The Kenyans worked together to try to box the Ugandan in, but as the race neared its end, he blew past them to finish with a commanding lead, giving Uganda its first medal of any color in these Games.
Read more: Nigeria's 12- year wait for Olympic gold
Kirui took silver and Wilson Kipsang Kiprotich took the bronze, with Eritrea-born American Meb Keflezighi coming fourth, about three minutes behind the winner.
The hosts snatched yet another boxing gold medal later Sunday, with super heavyweight Anthony Joshua winning gold for Britain. Italy, whose Roberto Cammarelle won silver, launched an appeal after the fight ended 18-18. Joshua was awarded victory on countback -- using the scores of all five judges, not just the middle three scores.
"It was a tough first round. The judges will always do their job and I do my job," the champion said. "I have had close decisions in other tournaments but I just take it on the chin."
The Italian said the decision was curious.
"I did everything I could. I don't understand the score," he said. "Where did they get all the points they gave him at the end?"
Team USA picked up another gold medal earlier, when Jacob Stephen Varner won the 96-kilogram freestyle wrestling contest.
"I came here to win a gold medal and that's what I've done," he said. "I played more defense then I wanted to, but it's awesome for the United States."
Uzbekistan's Artur Taymazov became first man to win three consecutive freestyle wrestling golds, defeating Davit Modzmanashvili of Georgia.
"I wanted to get the third gold," said Taymazov, who also won a silver at the Sydney Games in 2000. "There was also a time pressure, because I am 33. But it was my time."
At the 2000 Olympics, Greco-Roman wrestler Alexander Karelin won three straight golds and then a silver.
"I'm glad I have equaled his medal total," Taymazov said, "but he has won more world championships than I have won so I must do more over the next two seasons."