Hardy felt the need to justify his life's work in mathematics at this time mainly for two reasons. Firstly, at age 62, Hardy felt the approach of old age (he had survived a heart attack in 1939) and the decline of his mathematical creativity and skills. By devoting time to writing the Apology, Hardy was admitting that his own time as a creative mathematician was finished. In his foreword to the 1967 edition of the book, C. P. Snow describes the Apology as a passionate lament for creative powers that used to be and that will never come again . In Hardy's words, Exposition, criticism, appreciation, is work for second-rate minds. [...] It is a melancholy experience for a professional mathematician to find himself writing about mathematics. The function of a mathematician is to do something, to prove new theorems, to add to mathematics, and not to talk about what he or other mathematicians have done.
Secondly, at the start of the Second World War, Hardy, a committed pacifist, wanted to justify his belief that mathematics should be pursued for its own sake rather than for the sake of its applications. He wanted to write a book in which he would explain his mathematical philosophy to the next generation of mathematicians; that would defend mathematics by elaborating on the merits of pure mathematics solely, without having to resort to the attainments of applied mathematics in order to justify the overall importance of mathematics; and that would inspire the upcoming generations of pure mathematicians. Hardy was an atheist, and makes his justification not to God but to his fellow man.
Starting in 1914, he was the mentor of the Indian mathematician Srinivasa Ramanujan, a relationship that has become celebrated. Hardy almost immediately recognized Ramanujan's extraordinary albeit untutored brilliance, and Hardy and Ramanujan became close collaborators. In an interview by Paul Erdős, when Hardy was asked what his greatest contribution to mathematics was, Hardy unhesitatingly replied that it was the discovery of Ramanujan. He called their collaboration the one romantic incident in my life. 
As the most important influence Hardy cites the self-study of Cours d'analyse de l'École Polytechnique by the French mathematician Camille Jordan, through which he became acquainted with the more precise mathematics tradition in continental Europe. In 1900 he passed part II of the tripos and was awarded a fellowship. In 1903 he earned his M.A., which was the highest academic degree at English universities at that time. From 1906 onward he held the position of a lecturer where teaching six hours per week left him time for research. In 1919 he left Cambridge to take the Savilian Chair of Geometry at Oxford in the aftermath of the Bertrand Russell affair during World War I. He returned to Cambridge in 1931, where he was Sadleirian Professor until 1942.