There’s no reason for this difference, except if when you use the API you don’t collect the LoCs of all your projects, you forget some of them.
Did you compare the number of projects given in the Administration --> Projects --> Management screen (total number of projects at the bottom) and the number of projects for which your collected the LoCs through the APIs ?
When you use the APIs, do you first call api/projects/search to get the full list of projects (keys), before calling api/measures/component ?
The second reason fro discrepancy may be that SonarQube considers, for each project, the largest branch of all to compute the project LoCs. If your largest branch is not the main (~master) branch, then that can also explain why you have this difference.
This happens sometimes with companies using GitFlow branch model and have very little code on master and most of the code on develop
So to get the right project weight you should call api/measures/component?componentKey=<project>&metricKeys=ncloc&branch=<branchKey> for each branch and then keep the largest for the LoC count.
(Note that the branch parameter is an internal parameter, ie not formally part of the public API, but you can use it pretty safely)