Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / REST

REST tutorial: Call a REST Webservice from Wordpress

5.00/5 (1 vote)
9 Jan 2013CPOL5 min read 44.7K  
Rest tutorial: Call a REST webservice from Wordpress.

REST Tutorial

Hey guys, today I am going to write a rest tutorial in English, as I’m tryin to get this on CodeProject. I hope my German audience can follow as well! So let’s start, today i’ll have some thoughts on calling our webservices from wordpress, especially from a wordpress form.

Free Newsletter Service 

I will show you how to achieve a newsletter service in your Wordpress site using our REST webservice and your Wordpress website (you don’t need to use our REST webservice, you can use any webservice you like with the approach described in this tutorial, however it’s free and it is doing its job, so you can give it a try!). So here we go, first step will be to set up our wordpress form for our user, so he can subscribe to our newsletter.

Setting up the Newsletter Subscribe Form

So go to your Wordpress admin and create a new site with some HTML:

XML
<html>
<form method="post" action="" >
email: <input id="email" name="email" type="text" />
<input type="button" value="submit" id="submit" />
</form>
</html>

OK, it’s not the most beautiful form I’ve ever created, but it will do it for today. The action tag we will be filling in some minutes, so let’s get to the next step, which in theory would be to implement our webservice call. But before we do that, we have to set up our newsletter, otherwise our users wouldn’t get any newsletter.

Setting up the Newsletter

Let’s have a look at the webservice api description here. (You can also have a look at the WADL, but unfortunately SOAPUI doesn’t create my REST Requests properly and i haven’t figured out yet how to fix that, so the wadl won’t be very helpful here)

The saveNewsletter method of the newsletter service consumes 4 parameters for installing a new newsletter. So let’s create a document for sending a REST Post to the webservice. Create a new HTML file and put again some html in it:

XML
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="post" action="http://78.47.190.21:8080/newsletter/webresources/v1/Newsletter/saveNewsletter/">
            <input type="text" name="newsletterId" />
            <input type="text" name="senderEmail" />
            <textarea cols="40" rows="30" name="message"></textarea>
            <input type="text" name="nextSendDate" />
            <input type="hidden" name="userpasswordToken" value="your token goes here" />
            <input type="submit" />
        </form>
    </body>
</html>

Notice how every input element is named, as this is exactly the way how it should be. Every name equals just to the param name in the webservice. Also notice the hidden userpasswordToken element, which will authenticate you as proper user (switch the token with your personal token). You can get your personal userpasswordToken for free at our site. The nextSendDate Param is just an unix timestamp. (This is easy and exactly, so you don’t have to take care on how your date has to be formatted.) The call in the first line is just an example, you will have to adapt that to properly call the service. So we don’t need any php or other stuff to run that stuff rather than html, so if you have a local webserver installed you can run this from your localhost, pretty cool isn’t it. Again this form won’t be very beautiful for demo purpose, you are allowed to apply your design. Hit the submit button and a newsletter is set up and will be running on our servers, so you can use that for free. Now that the newsletter service is setup and running, we can proceed and add a receiver to that service, that will get our newsletter.

Implementing the Webservice Call to Add a Receiver

This is the part where we will call our service from wordpress. Again have a look at the webservice description. The saveNewsletterReceiver method of the newsletterReceiver service takes three parameters: The newsletterId of the newsletter we just set up, the email adress of the receiver and again a userpasswordToken to authenticate yourself being allowed to use the service. We will use curl to call the service. Create a new PHP file named saveReceiverRest.php and put that into it:

JavaScript
$receiver = $_POST['email'];
$userpasswordToken = "your token goes here again";
saveNewsletterReceiver(5,$receiver,$userpasswordToken);

function saveNewsletterReceiver($newsletterId, $receiverEmail,$userpasswordToken) {
    $serviceUrl = 'http://78.47.190.21:8080/newsletter/webresources/v1/NewsletterReceiver/saveNewsletterReceiver/';
    $curl = curl_init($serviceUrl);
    curl_setopt($curl, CURLOPT_POST, true);
    
    curl_setopt($curl, CURLOPT_POSTFIELDS, "newsletterId=" . $newsletterId . "&receiverEmail=" . $receiverEmail. "&userpasswordToken=" . $userpasswordToken);
    $curl_response = curl_exec($curl);
    curl_close($curl);
}

The first param is the id of the newsletter we set up in the step before. The second param is the email address, that the user will enter into the form, we created in the first step. Just to show you how the webservice looks on server side (in case you are going to write your own webservice) i will give you a look at the Java Code.

This is the Newsletter service for setting up a newsletter:

Java
package de.webservicejunkies.newsletter;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

@Path("/v1/Newsletter")
@Stateless
public class Newsletter extends AuthenticatedResource {

    @EJB
    RepositoryLocal repo;

    /**
     * sets up a newsletter or changes it
     * @param newsletterId - if the newsletterId is new, a new newsletter will 
     *   be set up. if the newsletterId is already known, the existing data will be changed
     * @param nextSendDate - the date on which the newsletter will be send next
     * @param message - the newsletter content (html allowed)
     * @param senderEmail - the email adress that will be used as sender adress 
     * @param userpasswordToken - token used to authenticate
     */
    @POST
    @Path("saveNewsletter")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void saveNewsletter(
            @FormParam("newsletterId") long newsletterId,
            @FormParam("nextSendDate") String nextSendDate,
            @FormParam("subject") String subject,
            @FormParam("message") String message,
            @FormParam("senderEmail") String senderEmail,
            @FormParam("userpasswordToken") String userpasswordToken) {
        de.hm.entity.entities3.Newsletter newsletter = repo.getNewsletter(newsletterId);
        /**
         * if the newsletter already exists, make sure some proper guy is altering it 
         * if it doesnt exist yet, make sure the guy has a valid token at least
         */
        String savedToken = null;
        try {
            savedToken = newsletter.getAuthentication().getUserPasswordToken();
        }
        catch (NullPointerException e) {
            // ignore - np
        }
        if ((newsletter != null
                && savedToken!=null && savedToken.equals(userpasswordToken)
                && authUser(userpasswordToken)) || (newsletter == null && authUser(userpasswordToken))) {
            repo.saveNewsletter(newsletterId, nextSendDate, subject, message, senderEmail, userpasswordToken);
        }
    }
}

and this will be the NewsletterReceiver Service for adding a receiver to that service:

Java
package de.webservicejunkies.newsletter;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

@Path("/v1/NewsletterReceiver")
@Stateless
public class NewsletterReceiver extends AuthenticatedResource {

    @EJB
    RepositoryLocal repo;

    /**
     * saves a new receiver for receiving newsletter email. 
     * before saving a receiver, a newsletter has to be set up using the newsletter service
     * @param newsletterId - the newsletterId of the newsletter set up by the newsletter service 
     * @param receiverEmail - the email adress of the receiver 
     * @param userpasswordToken - token used to authenticate
     */
    @POST
    @Path("saveNewsletterReceiver")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void saveNewsletterReceiver(
            @FormParam("newsletterId") long newsletterId,
            @FormParam("receiverEmail") String receiverEmail,
            @FormParam("userpasswordToken") String userpasswordToken) throws Exception {
        de.hm.entity.entities3.Newsletter newsletter = repo.getNewsletter(newsletterId);
        if (newsletter == null) {
            throw new Exception("that newsletter does not exist!");
        } else {
            try {
                String savedToken = newsletter.getAuthentication().getUserPasswordToken();
                if (savedToken.equals(userpasswordToken) && authUser(userpasswordToken)) {
                    repo.saveNewsletterReceiver(newsletterId, receiverEmail, userpasswordToken);
                }
            } catch (NullPointerException e) {
            }
        }

    }
}

Exception handling is not very nice also, will follow in v2. The class AuthenticatedResource just holds some logic for authenticating the user with the userpasswordToken (via method authUser()). I know this is not a very elegant way of solving authentication with REST but it was the fasted way to achieve that..im working on a better way these days.

So the last step will be to adapt that form, so the webservice can be called properly: Go to the form and change it, so it looks like that:

XML
<html>
<form method="post" action="saveReceiverRest.php" >
email: <input id="email" name="email" type="text" />
<input type="button" value="submit" id="submit" />
</form>
</html>

The repo EJB is just an EJB writing the stuff to database.

So that’s it! You can have that into any site of your wordpress website or any widget you want. If you now hit the submit button the entered email addy will get constantly bombed by the newsletter service. I would recommend to show some "You have been successfully added" message to the user, as soon as he hits the button, otherwise theres no feedback if anything happened after the click.

OK I hope you enjoyed this small rest tutorial and now have fun implementing that stuff, thanks for reading and your feedback will be very appreciated!

P.S: You will find your userpasswordToken here (notice that you need to be registered).

The post rest tutorial: Call a REST webservice from wordpress appeared first on webservice-junkies.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)