The chemical reactions and pathways involving heparin, any member of a group of glycosaminoglycans found mainly as an intracellular component of mast cells. They are similar to heparan sulfates but are of somewhat higher average Mr (6000-20000) and contain fewer N-acetyl groups and more N-sulfate and O-sulfate groups; they may be attached in the same manner to protein, forming proteoglycans. They consist predominantly of alternating alpha-(1->4)-linked D-galactose and N-acetyl-D-glucosamine-6-sulfate residues.