Monthly Archives: October 2014

RESTful Web Services with Web API

Web API is a very nice clean way to get a very robust RESTful web service set up. If you have not had a chance to look at it yet, now is your chance. In this post, I will set up a simple RESTful web service using Web API. I am using VS 2013. You can accomplish the same thing in 2012 using NuGet to download the Microsoft ASP.NET Web API package. 

 

Alright, since this is  blog post, lets build a blog api… We will set up the basic CRUD services for BlogPosts. Start by Creating a new project…. 

Screen Shot 2014 10 28 at 9 11 32 AM

For the purposes of this post, we are going to create an empty project. So select empty and then add the WebAPI references.

Screen Shot 2014 10 28 at 9 13 38 AM

Ok, so some stuff has happened as if by magic, so lets look around for a minute at the important stuff. 

Look in App_start and open WebApiConfig.cs. This has the routing config for your API. You will see a chunk of code that looks like this…

            config.Routes.MapHttpRoute(

                name: “DefaultApi”,

                routeTemplate: “api/{controller}/{id}”,

                defaults: new { id = RouteParameter.Optional }

            );

 

This is the routing rules that your API will follow. In this case, to access your API, you would would start in http://localhost/api. The next piece is the controller. WebAPI will look in the controllers folder for a controller that matches what is passed in here. So, http://localhost/api/posts will look in the controller folder for a PostsController and route to that. The id field is declared optional. We will do something with that in a minute…. 

Ok, so lets go over to the models folder for a minute and get a model created so we have a framework for what a post looks like. Right click on models and select add – > class… Lets call it Post

Screen Shot 2014 10 28 at 9 27 31 AM

 

For the purposes of this post, lets keep it fairly simple. We will add a few fields to Post so we have some data. Lets do Author, Title, Body, and an Array of Tags. Posts should look like this when added…

 public class Post

    {

        public string Author { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }

        public string[] Tags { get; set; }

    }

Ok, now that we know what a Post looks like, lets get some api routes built. Lets start by building a controller. Right click on the controllers folder and click add -> Controller. You will get a box with lots of options. You can have one created with the gets and posts already set up, but what is the fun in that. Just select an empty controller for now. 

Screen Shot 2014 10 28 at 10 04 23 AM

 

name it PostsController and click ok… Now you have an empty controller all ready to go. Lets start out first with some data to pass around. Lets create an array of posts to return. Drop in something like this…

public class PostsController : ApiController

    {

        Post[] posts = new Post[] {

            newPost {Author =“Jon”, Title =“Blogging For Dummies”,

                     Body =“A very short blog post”, Tags new string[] {“soft skills”, “beginner”}}, 

             newPost {Author =“Lee”, Title =“Blogging For Smart People”,

                      Body =“A shorter blog post”, Tags new string[] {“soft skills”, “Expert”}}

        };

 

Now that we have some data, lets set up our get route. This is where WebAPI really shines. For the generic “Get” on our API, all we need to do is create a method called get… yep, thats it. because we are returning a list of Posts, we set it up with a return type of IEnumerable<Post> and WebAPI will deal with all the rest. Your method will look like this…

public IEnumerable<Post> Get()

        {

            return posts;

        }

 

Yea, thats it… Web API will worry about all the rest. With that done, click run and lets get started.  

If you get a screen that looks like everything is broken, that means you did it right…. 

Screen Shot 2014 10 28 at 10 24 53 AM

Thats because you are pointing to just http://localhost… Remember that the controller is at /api/Posts. so update your url to localhost:<port>/api/posts and you should be set…

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfPost xmlns:i=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://schemas.datacontract.org/2004/07/BlogPost.Models”>
    <Post>
        <Author>Jon</Author>
        <Body>A very short blog post</Body>
        <Tags xmlns:d3p1=”http://schemas.microsoft.com/2003/10/Serialization/Arrays”>
             <d3p1:string>soft skills</d3p1:string>
             <d3p1:string>beginner</d3p1:string>
         </Tags>
         <Title>Blogging For Dummies</Title>
     </Post>
     <Post>
         <Author>Lee</Author>
         <Body>A shorter blog post</Body>
             <Tags xmlns:d3p1=”http://schemas.microsoft.com/2003/10/Serialization/Arrays”>
                  <d3p1:string>soft skills</d3p1:string>
                  <d3p1:string>Expert</d3p1:string>
            </Tags>
            <Title>Blogging For Smart People</Title>
     </Post>
</ArrayOfPost>

But wait, why is this XML, I want JSON… Don’t worry, WebAPI returns the data type that is being requested by the client. So if your client sends application/json it will get JSON back. But, I know you want to see JSON when you do it this way so here is a quick fix. add this line to your WebApiConfig and you will see json in the browser

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));

Ok, so just like that, we have a working basic API for Posts. In the next post, We will add the other verbs, and then get more complicated with repositories and dependency injection. Stay tuned… 

Quick application scaffolding with Express

Ok, maybe I am the only one who didn’t know this but getting a basic application scaffolding set up in Node is ridiculously easy…. Check this out.

 

In a terminal window.. Create a new directory… Called what you want. 

mkdir NewTestApp ; cd NewTestApp

install express globally so you can execute it from the command line. 

npm install -g express

now, express will create a full blown Node app with express, jade, all of your parsers, and routing with one simple command… 

express newAppName

Done, lots of stuff installed and ready to go. But, before you go anywhere, you need to get the dependancies installed. cd into the new directory and run npm install. 

cd newAppName && npm install

That will get everything installed and ready to go. The way it sets everything up to run is with a script in /bin/www that starts up the server on port 3000… To start it up, run this:

DEBUG=my-application ./bin/www

Done. Take a few minutes to look around and see how the routing is done but this approach will save you from having to redo all the requires and initial routing work every time you want to play with something. 

 

What is a Hypermedia API Anyway?

Hypermedia is one of those terms that get floated around every time a RESTful web services conversation starts up. Or maybe I am just terrible at dinner conversations…  At its core, Hypermedia refers to anything that is not text. So in HTML the hypermedia portion would be the image tags, hyperlinks, resources (css/javascript), etc… Thats great, but in APIs, you don’t see a lot of images getting pulled in. Its basically just JSON responses… So, where does Hypermedia come in to RESTful APIs?  Fielding put it this way… 

When I say hypertext, I mean the simultaneous presentation of information and controls such that the information becomes the affordance through which the user (or automaton) obtains choices and selects actions… Hypertext does not need to be HTML on a browser. Machines can follow links when they understand the data format and relationship types. –Roy Fielding

 

So, what he is saying here that in addition to presenting back the data, or information, you should also present back some controls to act on the data. 

Here is an example.  I will use a speaker/session interaction to show what I mean. 

A typical response to a “Speaker” request from an api would look like this…

{

    SpeakerId: 4982174123,

    Name:  “Jonathan Mills”

    Bio: “This is Jon’s Bio”

    Sessions: [{

        Title: “This is my session”,

        Description: “This session is awesome”

    }]

}

Ultimately, this is fine, but it does not help a developer understand what the API is trying to do without consulting lots of documentation. Adding in some “Hypermedia” or in Fielding’s words, some controls will add some clarity to the API consumer as to what options they have in using the API. Check out the response with some hypermedia added in. 

{

    _id: 4982174123,

    Name:  “Jonathan Mills”

    Bio: “This is Jon’s Bio”

    Sessions: [{

        _id: 12379485749

        Title: “This is my session”,

        Description: “This session is awesome”

        _links:{
           Details:{
              “href”:”http://localhost:8080/Sessions/Details/12379485749″
           }
        }

    }]

    _links:{
         ExtendedBio:{
             “href”:”http://localhost:8080/Speaker/Extended/4982174123″
         }
    }

}

Adding in the Hypermedia links, gives the API consumer a clear understanding of what other options they have when dealing with your API. 

Ok, now realistically, this is just one component of a larger conversation but this should give you a pretty good understanding of what someone is talking about next time they throw out that term… 

 

Responsive NavBars with Bootstrap

Creating responsive navigation can be painful. But with bootstrap, we can get something that looks nice and clean knocked out fairly quickly. In this post, I will walk you through the basics of getting a responsive navbar up and running. 

 

First things first, lets get some nav items in a list. 

 

<body>
    <ul>
        <li>Home</li>
        <li>About</li>
        <li>Contact Us</li>
        <li>Login</li>
    </ul>
</body>

Looking in the browser, it should look something like this… 

Screen Shot 2014 10 10 at 9 18 38 AM

 

Ok, not super awesome… But with just a few tags, this will start to look good…

Start by dropping bootstrap into your project. I use http://bower.io/ to manage all of my web dependancies, but you can get it from http://getbootstrap.com/

Now we include the bootstrap.css in our project. Your href will look different than mine….

<head lang=”en”>
<meta charset=”UTF-8″>
<title>BootStrap</title>
<link rel=”stylesheet” type=”text/css” href=”bower_components/bootstrap/dist/css/bootstrap.css”>
</head>

Your page should change slightly now due to different fonts from the css but for the most part its the same. 

Screen Shot 2014 10 10 at 9 37 22 AM

Now is where the magic happens. We are going to use some class attributes to set the whole thing up as a navbar. First we wrap the whole thing in a div with a class of “navbar”. We add in a class of navbar-default to add a little theme to it. You could use navbar-inverse instead to set a different feel.

The navbar will look for items with a “nav” and “navbar-nav” classes and style them appropriately, so we add those tags to the <ul>, In order for any of this to work… your list items must be links… So add that in too. It should look like this… 

<div class=”navbar navbar-default”>
    <ul class=”nav navbar-nav”>
        <li><a href=”#”>Home</a></li>
        <li><a href=”#”>About</a></li>
        <li><a href=”#”>Contact Us</a></li>
        <li><a href=”#”>Login</a></li>
    </ul>
</div>

The results would be pretty dramatic…

Screen Shot 2014 10 10 at 10 35 45 AM

Ok, don’t get too excited yet, we still have to make this thing responsive.  We start by creating a button with three bars… That seems to be the current “Click me, I am a menu” standard.  We are going to use the class “navbar-toggle” to have it only show up when your screen is small. You will have to shrink your browser size to see it. Add it in under your div, but before your <ul> like this…

<div class=”navbar navbar-default”>    
    <button type=”button” class=”navbar-toggle” >
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
    </button>
<ul class=”nav navbar-nav”>

….

Now, when your browser is small, it will look like this.. 

 

Screen Shot 2014 10 10 at 10 57 29 AM

Thats great and all, but we want it to replace the menu, not just appear, so now we have to break out the navbar-collapse class. create a new <div> with the class navbar-collapse, collapse,  and an id of navBarCollapse )the id can be anything you want… and move the list into that. We also add a “data-toggle” tag to the button and a “data-target” that points to the id of the list items.. It should now look like this.. 

<div class=”navbar navbar-default”>
    <button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”#navBarCollapse”>
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
    </button>

</div>

<div class=”navbar-collapse collapse” id=“navBarCollapse”>
    <ul class=”nav navbar-nav”>
        <li><a href=”#”>Home</a></li>
        <li><a href=”#”>About</a></li>
        <li><a href=”#”>Contact Us</a></li>
        <li><a href=”#”>Login</a></li>
    </ul>
</div>

 

Now, we need to be sure we pull in the bootstrap scripts and add jquery to make the drop downs work. 

<script src=”bower_components/jquery/dist/jquery.js”></script>
<script src=”bower_components/bootstrap/dist/js/bootstrap.js”></script>

When clicked, it should look like this..

.Screen Shot 2014 10 10 at 10 57 29 AM

That’s it. You should now have a fully responsive navbar… Let me know what you think. 

Seek out and Learn from feedback

Nothing is more scary than the criticism of your peers. Well, except maybe never improving on your skills. One of the most important steps you can take to improving yourself as a developer (or in anything really) is to actively seek out people to review what you have done, and honestly listen to what they have to say. We have all sat in code reviews where you hear people tearing down what you have done, or questioning everything little thing. The first gut reaction to that situation is to throw up a wall, dig a trench, and defend your code to the death. If we want to improve, I mean really get better at what we do, we need to embrace those opportunities to have other people look at our stuff, and listen as they tear it apart. Yes, they will not always be right. Sometimes people are just nitpick everything. But going in with an open mind and a desire to learn will drastically change your outlook on those situations. 

If you really want to get better, push some code out to github and send a tweet like this… “Just tried consuming secure rest apis using auth-tokens in angular and would love some feedback.” #Angular @angularjs…. Or post to reddit programming or stack overflow with a request for feedback. No matter what you do, actively seek constructive feedback from others. Its absolutely the best way to keep yourself moving forward.