Independence from Spain was declared in 1821 and the country became an independent republic in 1838 .