Determining the atmospheric structure and chemical composition of an exoplanet remains a formidable goal. Fortunately, advancements in the study of exoplanets and their atmospheres have come in the form of direct imaging—spatially resolving the planet from its parent star—which enables high-resolution spectroscopy of self-luminous planets in jovian-like orbits. Here, we present a spectrum with numerous, well-resolved molecular lines from both water and carbon monoxide from a massive planet orbiting less than 40 astronomical units from the star HR 8799. These data reveal the planet's chemical composition, atmospheric structure, and surface gravity, confirming that it is indeed a young planet. The spectral lines suggest an atmospheric carbon-to-oxygen ratio that is greater than that of the host star, providing hints about the planet's formation.