Share this blog!

In this blog post, we will design a simple Rest API from scratch. We will implement it, deploy it as a service and then invoke the service using WSO2 platform.

Design the API

The API is the interface that will be in between your users and your service. From the perspective of a business mind, this is the most critical step. You need to sit down, take a piece of paper and jot down how you want your users (or customers most probably) to use your API. You need to document your requirements, what you plan to provide and your goals and outline the communication between the user and your service.

In this post, I will be creating only one API for demonstration purposes but in general, the requirements maybe more complex.

  1. Purpose: Say hi to the user, call him by his name
  2. What should be returned to the user: "Hi Sachi, welcome to Com Exile!"
  3. Any inputs? The name

The above is a basic idea, it can be extended to include factors such as what should happen if something goes wrong (errors) etc.

In the above, the API  requires an input from the user, we can use a GET call with the endpoint format "hi/{name}".

Once the definitions are outlined, we can start writing the service definition. OpenAPI or Swagger, is an API description format that defines all the required specifications in APIs. The API descriptions can be written in either yaml or json. Json is suitable for machine generate code whereas yaml is for API definitions that are written by humans (because it is easier to read and write).

The following is a sample yaml written to represent our API.

swagger: "2.0"
info:
  description: "This is a simple server Com Exile."
  version: "1.0.0"
  title: "Com Exile" 
paths:
  /hi/{name}:
    get: 
      summary: "Say hi"
      description: "This API says hi to the user" 
      produces: 
      - "application/json"
      parameters:
      - name: "name"
        in: "path"
        description: "Name of the user"
        required: true
        type: "string" 
      responses:
        200:
          description: "successful operation"
          schema:
            type: "string"
            example: "Hi, welcome to Com Exile" 
        400:
          description: "Invalid input supplied"

The above yaml contains the basic fields. Refer this OpenAPI map for a full description of the specification. You can use swagger editor to create it or copy and paste it to a "hi.yaml" file using a text editor.

Generate code skeleton

Now let's create a webapp that implements the API logic we have defined.

Step 1: Create a JAX-RS Project

Use the command

mvn archetype:generate -Dfilter=org.apache.cxf.archetype:

as described in this Apache documentation and create a project.

Step 2: Download required maven JARs

Clone this git repo and build using mvn clean install, which will install the required jars to run the swagger-to-cfx maven plugin.

Step 3: Generate server stub

In order to generate the code stub using swagger-to-cfx plugin, you need to import our "hi.yaml" file into the project. 

Create a resources folder in "src/main" in the project we created earlier and copy and paste the "hi.yaml" file there.

Then, add the following inside <plugins> in your "pom.xml" file, which imports the required resources.


<plugin>
    <groupId>org.wso2.maven.plugins</groupId>
    <artifactId>swagger2cxf-maven-plugin</artifactId>
    <version>1.0-SNAPSHOT</version>
    <configuration>
        <inputSpec>${project.basedir}/src/main/resources/hi.yaml</inputSpec> 
    </configuration>
</plugin>


Then update the build-helper-maven-plugin as follows:


<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.9.1</version>
    <executions>
        <execution>
            <id>reserve-network-port</id>
            <goals>
                <goal>reserve-network-port</goal>
            </goals>
            <phase>process-test-resources</phase>
            <configuration>
                <portNames>
                    <portName>test.server.port</portName>
                </portNames>
            </configuration>
        </execution>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>src/gen/java</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>


Then run the following command to generate the code skeleton.

mvn swagger2cxf:generate

Implement code logic

When the code skeleton was created, you would notice the classes with method signatures for each API we defined. Modify the method body of the impl class in "src/main/java/artifactid.impl"as follows.


public class HiApiServiceImpl extends HiApiService {
    @Override
    public Response hiNameGet(String name) {
        String response = "Hi " + name + ", welcome to Com Exile!";
        return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, response)).build();
    }
}


The above is a simple scenario with a String concatenation. Remember that typical API implementations would require more complex logic implementations.

Build the project

To build the project war file, add the following in the pom file.

<plugin>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.2</version>
  <configuration>
     <webResources>
        <resource>
           <directory>src/main/webapp</directory>
        </resource>
     </webResources>
     <warName>HiAPI</warName>
  </configuration>
</plugin>


Then run mvn clean install to generate the war file.

Deploy the project

To deploy your project, you can use WSO2 Application Server, simply run the server and open "Web Applications" from the management console and upload the war file. Read more about it on WSO2 docs.




Invoke the API

Once deployed, you can try out the API you created by invoking it. If you used WSO2 Application server to deploy, you will see the endpoint URL in the webapp details page in the management console.



You can either use postman to invoke your API as follows.

Or you can even try the following curl command in your command prompt.

curl -X GET http://172.17.0.1:9763/HiAPI/1.0.0/hi/sachi




Cheers!

What is OAuth?

OAuth is an open standard that facilitate Internet users to allow websites and applications to access their information without giving them the passwords.  As a simple example, consider Facebook using OAuth so that a Facebook user can tell Facebook "I know this third party web service, allow it to view my profile".

The following is a sample prompt from Facebook which you might be already familiar with:


OpenID is another similar standard. The basic objective of Oauth is to provide authorization whereas OpenID is there to provide authentication. What does that mean?

Authentication vs authorization

Authentication is focused on proving the identity of a person or a resource whereas authorization deals with confirming the privileges that person or resource has. Simply put, authentication is about who somebody is and authorization is about what he is allowed to do.


OAuth is all about dealing with employees trying to enter into the building.

Now let's take a look at the current situation of OAuth.

What is OAuth 2?

OAuth 2 is the second version of OAuth. However, version 2 is not backward compatible with version 1 and it focuses more on developer simplicity. OAuth 2 has expanded its wings to support non web applications, which was considered as a limitation of OAuth 1.

How does OAuth 2 work?

The following represents the abstract protocol flow in OAuth.
Source: Digital Ocean
But the above is useless (a moo point as Joey would say) if you don't know about the OAuth roles.

OAuth Roles

  1. Resource owner (User) - The user that the account information belong to. He authorized an application to access their account.
  2. Client Application - The application that wants to access the user's account.
  3. Resource / Authourization Server (API) - The resource server is the one that maintains the user's account. The authorization server is the one that checks the accessibility and grant access to required parties.  
In an example where you tell Facebook, "I know this XYZ service, allow it to view my profile.", you are the Resource Owner, XYZ is the Client Application and Facebook is the Resource/ Authorization Server.



Now the abstract protocol flow makes some sense, doesn't it?



  1. The application asks the user's permission to call the resource server.
  2. The user grants permission - there are multiple ways this grant can be allowed, which will be explained next.
  3. The application shows the server "Hey look, I have the permission, let me in".
  4. The doorman of the server checks the permission and gives an access token to the application "Okay, you can go in, show this access token when you're inside".  
  5. The application goes in, and shows the access token to the one that keeps the information he wants.
  6. The information is provided to the application.
This SO answer gives an interesting explanation about how OAuth2 works.

OAuth 2 Grants

In the above scenario, when the application asks the user to give access to the account information, the user could decide on how to give the required permission. So basically, a grant is a method of acquiring an access token. An access token always have an expiration time and it is usually accompanied by a refresh token, who is there to help refresh the access token when it is expired.

OAuth 2 supports 4 grant types:

  1. Authorization Code grant - This is optimized for server-side applications and you may have already met this if you have ever signed into an application using Facebook or Google. This can maintain the confidentiality of the client-secret.
  2. Implicit grant - This is different from the above because this is mostly used in mobile or single-page web applications, where maintaining the client-secret is a problem. In this method, the server returns an access token (instead of authorization code like before) and the server does not return a refresh token.
  3. Resource Owner Password Credentials grant - This is used only if the application is trusted by the user and the user provides the credentials (username and password) which are used to obtain the access token.
  4. Client Credentials grant - This grant type allows an application to access its own service account on the server. This is typically machine-to-machine authentication where user's permission is not required.

Which grant should I use?

If you're the client application developer, this is the obvious question that would hop in your mind. In his blog post, Alex Bilbie explains how to decide on which grant type to be used, based on the client type you're using and other factors. 

Source: Alex Bilbie

Cheers!
Next PostNewer Posts Previous PostOlder Posts Home