How do I create a view from the user interface, and get the code to create it programmatically?
That is a feature that the Views module already has. In Drupal 7, you need to follow these steps:


In the page listing all the views defined in a site, select the "Export" operation


In the next page, the Views module will show you the code that defines the view.


This is only the code that defines the views.

Another way, is the following one; in this case, you get the complete code to use to write a module.


Enable the Bulk Export module that is listed under the modules that are part of the Chaos Tools Suite module
On admin/structure/bulk-export, select the view(s) you want to export in a module, and enter the name of the module


After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view


In Drupal 6, you need to follow these steps:


Enable the View Exporter module that is part of the Views module (I am referring to version 6.x-3.0.)
On admin/build/views/tools/export, select the view(s) you want to export in a module, and enter the name of the module


After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view