MADRID—Spain’s Supreme Court sentenced a popular singer to one year in prison for Twitter messages that were deemed to glorify terrorism and humiliate its victims, the latest application of an antiterrorism law that is testing the boundaries of free speech here.

César Montaña Lehman, who leads the rap metal band Def Con Dos and goes by the artistic name César Strawberry, is one of dozens of Spanish performers, poets and ordinary social-media users who have been prosecuted under the law in recent years.

In tweets posted over a three-month period in 2013 and 2014, Mr. Montaña joked about past terrorist attacks and mused about future ones. He wrote of giving Spain’s king at the time, Juan Carlos I, a cake bomb for his birthday. He said the views of some politicians made him “yearn for GRAPO,” a long-defunct far-left terrorist group. One politician who had once been held by the armed Basque separatist group ETA, he said, “needs to be kidnapped right now.”

During a trial in 2015, Mr. Montaña said that he had never supported terrorism and that he “used humor, sarcasm and irony to try to disconcert people” and challenge prevailing political and religious dogma.

Spain’s National Court agreed that he wasn’t defending violence and acquitted him. The prosecutor appealed, and the Supreme Court convicted Mr. Montaña, ruling that the intent behind his tweets, which it said had reached more than 8,000 followers, was immaterial. The messages in themselves, the five-judge panel wrote, “feed hate speech and legitimize terrorism as a formula for resolving social conflict.”