Sin categoría

Using the Magento REST api in Java with Scribe


Hi, in this short tutorial we are going to use the new REST api of the Magento e-commerce platform using the Scribe api under the Java platform.

In this new release of Magento, version 1.7, they provide a new REST api with OAuth 1.0a authorization scheme, so in order to make the calls to their api we need a framework that supports it, we use the good Scribe framework from Pablo Fernandez to accomplish this task.

First we have to generate the REST roles and consumers in the Magento dashboard, the roles are going to map the resources inside Magento that this role need access to and the consumer is going to represent the keys to be used inside our custom app that use the Scribe framework.

In order to add consumers to Magento from the REST api we create an OAuth REST Consumer where it will store the keys to be used by our app. We create them using the Magento dashboard and selectingSystem > Web Services > REST – OAuth Consumers like in the next image.

m3

Magento automatically generates the keys and we take note on these values.

m4

Now we create and admin role inside Magento selecting System > Web Services > REST Roles as showing in the next picture.

m1

We select the resources or all of them in order to access them as in the following image.

m2

This role we are going to associate to our OAuth Consumer key already created in the first step like in the following picture.

m5

Now we create a command line app that retrieves the request token using the OAuth consumer keys from Magento.

First all download the source of the Scribe framework from GitHub and create a new project inside Eclipse, the only requirement is to have the commons codec jar file from Apache in order to compile it like is showing in the next picture.

m6

Once compiled the Scribe framework we need to implement an abstract class that represents our interaction with the OAuth 1.0a protocol and the particular implementation of Magento and make use of the keys provided there so we can get the request_token, the access_token and the token_secret on thethree-legged and sometimes cumbersome schema of OAuth 1.0a.

So we extend the DefaultApi10a class from Scribe and provide the endpoints and authorization URL for our own Magento server like in the following code.

/* 
 * @author jerry
 */
      public static final class MagentoThreeLeggedOAuth extends DefaultApi10a {
		private static final String BASE_URL = "http://your.magentohost.com/";

		@Override
		public String getRequestTokenEndpoint() {
			return BASE_URL + "oauth/initiate";
		}

		@Override
		public String getAccessTokenEndpoint() {
			return BASE_URL + "oauth/token";
		}

		@Override
		public String getAuthorizationUrl(Token requestToken) {
			return BASE_URL + "admin/oauth_authorize?oauth_token="
					+ requestToken.getToken(); //this implementation is for admin roles only...
		}

	}

This is an inner class used in our main app that will invoke the request token, but first we setup the client that is going to talk to the Magento OAuth subsystem.

/**
 * @author jerry
 */
public final class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final String MAGENTO_API_KEY = "THE_MAGENTO_KEY_FROM_OAUTH_CONSUMERS";
		final String MAGENTO_API_SECRET = "THE_MAGENTO_SECRET_FROM_OAUTH_CONSUMERS";
		final String MAGENTO_REST_API_URL = "http://your.magentohost.com/api/rest";

Once we have defined our keys and our own Magento server we call the OAuth client with our own implementation of the OAuth 1.0a protocol like in the following.

// three-legged oauth
		OAuthService service = new ServiceBuilder()
				.provider(MagentoThreeLeggedOAuth.class)
				.apiKey(MAGENTO_API_KEY)
				.apiSecret(MAGENTO_API_SECRET)
				.debug()
				.build();

Now we can ask for the request_token as follows.

// start
		Scanner in = new Scanner(System.in);
		System.out.println("Magento's OAuth Workflow");
		System.out.println();
		// Obtain the Request Token
		System.out.println("Fetching the Request Token...");
		Token requestToken = service.getRequestToken();
		System.out.println("Got the Request Token!");
		System.out.println();

Now we ask for the authorization URL as follows.

// Obtain the Authorization URL
		System.out.println("Fetching the Authorization URL...");
		String authorizationUrl = service.getAuthorizationUrl(requestToken);
		System.out.println("Got the Authorization URL!");
		System.out.println("Now go and authorize Main here:");
		System.out.println(authorizationUrl);
		System.out.println("And paste the authorization code here");
		System.out.print(">>");
		Verifier verifier = new Verifier(in.nextLine());
		System.out.println();

If we run the program at this moment is going to print the URL to be authorized to your Magento server and waiting for the code to be displayed, like in the following run of the code.

m7

So copy the URL from the console and paste in the browser and you should see the page from Magento to authorize this app to access the resources defined previously in the dashboard like in the following image.

m8

Once we paste this number in our program we should be able to trade the request token for the access token in order to have the key to access the protected resources as follows.

// Trade the Request Token and Verfier for the Access Token
		System.out.println("Trading the Request Token for an Access Token...");
		Token accessToken = service.getAccessToken(requestToken, verifier);
		System.out.println("Got the Access Token!");
		System.out.println("(if your curious it looks like this: "
				+ accessToken + " )");
		System.out.println();

Now we can store this access token in our preferred storage system or we can continue and retrieve using this token and a GET request, for example, the list of products from Magento like in the next sample code.

// Now let's go and ask for a protected resource!
               OAuthRequest request = new OAuthRequest(Verb.GET, MAGENTO_REST_API_URL+ "/products?limit=2");
		service.signRequest(accessToken, request);
		Response response = request.send();
		System.out.println();
		System.out.println(response.getCode());
		System.out.println(response.getBody());
                System.out.println();
    }
}

This request will display in JSON format a list of products for selling in the Magento store like in the following picture.

m9

Now, we are administrators and we have the power of create consumers, the Magento REST api provide this capability but it seems that it is still a little buggy, but anyway, we just need to POST an XML with the information of the customer like in the following code using our previous stored access token like in the following snippet code.

OAuthRequest request = new OAuthRequest(Verb.POST, MAGENTO_REST_API_URL+"/customers");
		request.addHeader("Content_Type", "text/xml");//this is a nasty bug in the current Magento implementation...we have to sent over
                final String user = "<!--?xml version=\"1.0\"?-->" +
									"<magento_api>" +
											"<firstname>Gerardo</firstname>" +
											"<lastname>Martinez</lastname>" +
											"<password>123123q</password>" +
											"<email>jerry@example.com</email>" +
											"<website_id>1</website_id>" +
											"<group_id>1</group_id>" +
									"</magento_api>";
		request.addPayload(user);
		service.signRequest(accessToken, request);
		Response response = request.send();
		System.out.println();
		System.out.println(response.getCode());
		System.out.println(response.getBody());

This particular request will produce a JSON message error in the current version but if we take a look at the Magento dashboard in the Consumers tab it will be there.

Happy coding 🙂

Estándar

9 comentarios en “Using the Magento REST api in Java with Scribe

  1. Excellent tutorial! Just to correct a typo in your code, where you have set ‘Content_Type’, this should be Content-type (note the hyphen).

    This was breaking my code and returning an ‘invalid signature’ error for me 🙂

    Cheers,

    Mike

  2. scott dijo:

    Seems like I have followed your instruction exactly, got an accessToken, but I cannot not get products:
    400 Bad Request

    Bad Request
    Your browser sent a request that this server could not understand.
    Any suggestion?

  3. Pingback: Android REST client for Magento

  4. Pingback: Magento Rest API | Ralph's Open Source Blog

  5. Jerry dijo:

    I followed each and every step above but still I am getting 404 not found error. Even in chrome postman extension I am getting 404 not found exception. Do you have any idea that where I am making mistake??

  6. Ivo Danic Garrido dijo:

    Hi,
    Hi, im new using java, but the way you explained it seem very easy! But i’ve a question, how should i add the scribe library adn how i compile it?

Deja un comentario