The Summer of Sam ended 40 years ago with a boozy bash at police headquarters — courtesy of a mayoral “amnesty’’ that lifted the no-liquor policy there for just that night.

David Berkowitz was sitting handcuffed and grinning like a loon in the Chief of Detective’s Office conference room on the 13th floor of 1 Police Plaza, as booze flowed down the hall, sources recalled to The Post.

“I saw Mayor Beame, and I said to him, ‘You know, Mr. Mayor, there is a prohibition from having alcohol in police facilities,’ ” said then-Capt. Joe Borrelli, describing the pair’s wink-and-nod chat — a never-before-publicized chapter in the Son of Sam saga.

“He smiled. And he handed me two $100 bills and said, ‘We will waive that tonight. Buy the boys a drink,’ ” remembered Borrelli, one of the top investigators on the Son of Sam case.

Mayor Abe Beame knew his police had been under a terrible strain. Berkowitz had murdered six people and wounded seven others over the prior 12 months, leaving the city in a state of fear that sweltering summer.

Some 200 cops worked the case, chasing thousands of dead-end leads.

Then at 10 p.m. on Aug. 10, 1977, Berkowitz walked out of his Yonkers apartment — and into the arms of waiting cops.

They had found him in part thanks to a parking ticket that had been left on the windshield of his yellow Ford Galaxie when he parked at the scene of his final murder.

“What took you so long?” Berkowitz infamously asked detectives at the scene.

Frank McLaughlin, the NYPD spokesman at the time, said he had a running bet with local bar owner Roy Barnard that detectives would catch the Son of Sam. The agreement was that when the killer was caught, Barnard would throw the cops a party.

The night of Berkowitz’s bust, Barnard said, he went to 1 Police Plaza, and “McLaughlin was talking to the press, but he looked at me and smiled.”

“I called my bar, Jim Brady’s, and told them I need a couple of cases of beer, bottles of rye, scotch, vodka, gin, a case of glasses and lots of ice.”

McLaughlin said he asked one of Beame’s deputy mayors, Stanley Friedman, for two $100 bills. He gave them to Beame, who handed them to Borrelli and told him to buy a round.

Barnard ended up paying “for all the liquor, so I gave Friedman back the money later,’’ McLaughlin said.

A bar was set up in a conference room, and case detectives and reporters began packing the place.

“Calls were coming from all over the world. At one point, there was a call from England, and Frank told me, ‘Here, talk to this guy.’ I was even quoted in the Irish Times as a police spokesman!”

When Berkowitz was finally caught, Borrelli, who eventually became chief of detectives, knew the cops had their man. But he was still waiting on fingerprint tests to come back on one of Son of Sam’s notes to link it to Berkowitz.

“I waited a few hours — until I got a fingerprint match and a ballistic match on the gun — before I had a scotch,’’ Borrelli recalled.