We can use the Legendre Transform to convert between Lagrangian Mechanics and Hamiltonian mechanics. Since position and momentum are conjugate variables, we can convert the Lagrangian and the Hamiltonian .
A detailed explanation on this conversion can be found on NYU’s lecture notes for mechanics, lecture 6.