A particular key is defined far more by its 'home', 'place of rest', than which notes are included in the tune involved.
It's a partial truth that most melodies will mostly use diatonic (belonging to the key) notes, as they are all 'part of the specific set'.
However, what about when the composer wants to use one of the five other notes that 'don't belong'? What are they supposed to do then? There is a very, very small percentage of songs/pieces that don't have those chromatic notes in them, a lot of children's songs, for example. To keep them simple, but often on the edge of boring after a while!
So, including those extra notes is a necessity, but - if one in particular keeps on cropping up, and coincides with a different home place, then it's time to ask whether in fact the tune has been written in the correct key after all.