SAN FRANCISCO — San Francisco on Tuesday became the first city in the country to sue President Trump over his order to withhold federal funding from so-called sanctuary cities, saying the order was unconstitutional.

In a lawsuit filed with the United States District Court of the Northern District of California, San Francisco’s city attorney, Dennis Herrera, requested an injunction on the Trump administration’s attempted crackdown on sanctuary cities, which limit city agencies and local law enforcement from assisting in the enforcement of federal immigration laws.

“You can’t put a gun to the head of states and localities to get them to comply with what you might want at the federal level,” Mr. Herrera said.

The Trump order says it is in the interest of public safety for local officials to cooperate with federal immigration authorities and seeks to withhold federal grants from municipalities that have sanctuary city policies.