An effective swing trajectory of legged robots is different from the swing trajectories of humans or animals because of different dynamic characteristics. Therefore, it is important to find optimal parameters through experiments. This paper proposes a real-time nonlinear programming (RTNLP) method for optimization of the swing trajectory of the legged robot. For parameterization of the trajectory, the swing trajectory is approximated to parabolic and cubic spline curves. The robotic leg is position-controlled by a high-gain controller, and a cost function is selected such that the sum of the motor inputs and tracking errors at each joint is minimized. A simplified dynamic model is used to simulate the dynamics of a robotic leg. The purpose of the simulation is to find the feasibility of the optimization problem before an actual experiment occurs. Finally, an experiment is carried out on a real robotic leg with two degrees of freedom. For both the simulation and the experiment, the design variables converge to a feasible point, reducing the cost value.