Swagger-codegen is a powerful Java library which can generate both server stubs and API clients from swagger definitions. This can dramatically ease the difficulty and cost of generating clients for any specific language. To get started and generate your first client, you’ll first want to grab an instance-specific copy of one of Marketo’s Swagger Definitions. Go here and input the Munchkin ID from the instance you want to test with. Start with the identity definition.
Now that you have a definition specific for your instance, you’ll need to download and install swagger-codegen. The process is specific to your operating system, and you can get the instructions here
With the default settings, codegen will output a client covering all of the provided endpoints and models. These are typically managed through a class called DefaultApi, containing methods for calling the available endpoints with examples provided in a ‘docs’ folder (not all languages include templates for this by default).
Now let’s build the first client. Create a folder where you want your code to live, and go there in your terminal session and use the generate command to build a client in the language that you want (we’ll assume you’ve used the homebrew install method):
1 |
swagger-codegen generate -i $definitionLocation -l $yourLanguage -o $yourLocation |
This will output the client code into your desired location.
Now let’s look at using this to call the identity endpoint and get an access token:
123456789101112public static void main(String[] args){String client_id = args[0];String client_secret = args[1];ApiClient client = new ApiClient();DefaultApi id = new DefaultApi();try {String token = id.identityOauthTokenGet(client_id, client_secret, "client_credentials").getAccessToken();System.out.println(token);} catch (ApiException e) {e.printStackTrace();}}
-
123456789101112131415<?phprequire_once(__DIR__ . '/vendor/autoload.php');$api_instance = new Swagger\Client\Api\DefaultApi();$client_id = "client_id_example";$client_secret = "client_secret_example";$grant_type = "grant_type_example";try {$result = $api_instance->identityOauthTokenGet($client_id, $client_secret, $grant_type);print_r($result->getAccessToken);} catch (Exception $e) {echo 'Exception when calling DefaultApi->identityOauthTokenGet: ', $e->getMessage(), "\n";}?>
-
123456789101112public static void Main(string[] args){string clientId = "CHANGE ME";string clientSecret = "CHANGE ME";IdentityApi instance = new IdentityApi();ResponseOfIdentity response = instance.IdentityUsingGET(clientId, clientSecret, "client_credentials");string message = string.Format("Access Token: {0}, Expires In: {1}, Scope: {2}, Token Type: {3}",response.AccessToken, response.ExpiresIn, response.Scope, response.TokenType);Console.WriteLine(message);}
Now that we know how to get authorized, we’ll take a look into more advanced use cases of auto-generated clients in the coming weeks.