To be able to keep farm animals legally, you need a ´Código de Explotación Ganadera´ from the government of your autonomous region. A farm licence registration, basically, that has certain requisites to be met for each species of farm animals individually.
The requisites involve animal welfare, so housing, water supply, transport but also environmental issues like waste disposal management. Depending on your location (near a river for example) the latter in particular could be more complicated to meet.
The Codigo´s are registered in the Autonomous Registro de Explotaciones Ganaderas.
The first port of call for information would be your local vet as he can provide you with the necessary paperwork or at least, direct you to the regional office dealing with this.
Contrary to public belief (especially amongst the farming families in small villages) there is no exemption in Spanish legislation for small holdings, raising only a couple of pigs, goats, sheep or rabbits for a household´s consumption. There used to be, but with the introduction of EU Directives, this has disappeared, sadly.
The fines for holding even one of a species of farm animals that is not mentioned on the Código are 3.000 euros per species detected or denounced. It´s important to note that the licences/Código should be in place before the first animal is in place.
There is also an obligation to get a licence for chickens, but most don´t bother with an official ´Codigo´ for those, but you should apply for a licence from Town Hall as they keep a register just in case they need to issue special measures when there is another ´bird flu scare´, for example.
More info for Andalucia
for other regions, just google ´codigo de explotación ganadera´ followed by the name of your autonomous region.