Code Samples

This page contains a number of small code samples. These samples demonstrate the process of connecting to our server, using our API, and testing a comment.

These samples do not contain error checking, but may be useful starting points for future development.

Perl Sample

The following sample submits a simple comment to the JSON API we present:


#!/usr/bin/perl

use strict;
use warnings;

use JSON;
use LWP::Simple;

#
#  The comment we're testing.  We store this in a hash, but submit
# the JSON-encoded version.
#
my %params = ( ip      => "192.168.1.1",
               site    => "http://example.com",
               comment => "You suck"
             );

#
#  Serialize the parameters
#
my $json = encode_json( \%params );

#
#  We're going to use a HTTP POST.
#
my $req = HTTP::Request->new( 'POST',
                              "http://test.blogspam.net:9999/"  );
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );

#
#  Send the request.
#
my $lwp      = LWP::UserAgent->new;
my $response = $lwp->request( $req );

#
#  Show the result which was received.
#
my $code   = $response->code;
my $result = $response->decoded_content;

print "Code: $code - $result\n";


[Download this sample]

Python Sample

The following sample uses Python to submit a comment for testing, again using the new/recommended JSON API:


#!/usr/bin/python

# sudo apt-get install python-requests | python3-requests
import requests

import json

params = {'site':   'http://my.blog.example.com/',
          'name': 'Bob SMith',
          'email': 'bob@example.com',
          'comment':  'This is my blog comment'}

headers = {'Content-type': 'application/json',
           'Accept': 'text/plain'}

r = requests.post("http://test.blogspam.net:9999",
                  data=json.dumps(params),
                  headers=headers)

print r.text

[Download this sample]

Ruby Sample

The following sample uses Ruby to submit a comment for testing.


require "net/http"
require "uri"
require 'json'



#
# The comment we're testing
#
message = {
  "ip"      => "1.2.3.33",
  "site"    => "http://blog.example.com",
  "name"    => "Anonymous",
  "comment" => "This is my comment-body, I like to submit comments"
}

#
#  Build up the request.
#
uri = URI("http://test.blogspam.net:9999/")
req = Net::HTTP::Post.new(uri.path)

#
# Set the body
#
req.body = message.to_json
puts "Sending: #{req.body}"

#
# Make the request.
#
res = Net::HTTP.start(uri.host, uri.port) do |http|
  http.request req
end

#
#  If it succeeded print the response.
#
if ( res.code.to_i == 200 )
  obj = JSON.parse res.body
  if ( obj["result"] =~ /spam/i )
    puts "Rejecting spam Comment: #{obj["reason"]}"
  else
    puts "This comment is OK"
  end
end


[Download this sample]