Share this blog!

Beginners Guide to Rest API Development

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!
Next PostNewer Post Previous PostOlder Post Home

1 comment:

  1. can you put the code in some github repository? thanks...

    ReplyDelete