If you copy a large block of code somewhere, you should also delete the original and modify the function so that it can be called from both locations. Copy-paste-edit is a very bad pattern for maintainability.

In this particular case, it looks like you needed to pull the code out so you could respond with json that encoded the error messages instead of showing them to the user in html with `messages.error`. It seems like if this works well, you can now delete the code in the original place and have that call and wrap this code with calls to `messages.error`. You would then of course need to test that both the UI method and the new curl method work.