Common misconception. Scarlatti's 555 keyboard sonatas were composed before his Spanish period—during his years in Portugal (1719–1729) and Italy.
In Madrid (1729–1757), he served Queen Maria Barbara as court musician and keyboard teacher. His output there focused on:
The sonatas? Likely composed for his Portuguese pupil, the Infanta Maria Barbara—brought to Spain as teaching material, not new creations.
Spain gave him security. Portugal and Italy gave us the sonatas.