Powered by
/src$ make
  • Home
  • About
  • Directory
  • Contact
  • Home
  • About
  • Directory
  • Contact

How To Make An API Using Java

2/7/2018

 
To watch the youtube video where I go through this tutorial, click here. 

Introduction: Making An API Using Java

If you're new here, then we've already had a blog post on what APIs are, and we've even seen how to plan and define the specifications for an API using Swagger. At this point, we need to actually code up the API so that we can put it on a server. Of course, one of the most popular programming languages to do that is Java. 

If you're not familiar, then go through the video series where we learn about Java. It's also in that series where we learn about the most necessary tool for creating APIs: Spring. Of course, we're going to make an API with the specifications that we've defined from the previous blog posts, but we need to start somewhere. 

Start Off With A Basic Spring Project Deployed on Heroku

We're going to start our API by creating a basic Java Spring project. I already have a video where we do exactly that, so watch the video if you're unfamiliar with this process. The base project can be found here, on github, if you need the code. To get the code from github, in the terminal: 
git clone https://github.com/srcmake/java-base-api
cd java-base-api
The most important things to notice in the project is that it's built using Maven, it has Spring as the API library, and it has one simple mapping for now that returns a string. 
While we're at it, push our project to Heroku. If you haven't already, in the terminal for Ubuntu 16.04 the commands for installing Heroku are:
sudo add-apt-repository "deb https://cli-assets.heroku.com/branches/stable/apt ./"
curl -L https://cli-assets.heroku.com/apt/release.key | sudo apt-key add -
sudo apt-get update
sudo apt-get install heroku
(If you're not using Ubuntu, then find the commands to install Heroku from here.) Install git if you don't already have it.
sudo apt-get install git
If you don't have an account with Heroku, then go to their website and make one. Login to heroku.
heroku login
Create the app on heroku's servers.
heroku create
Next, push our project up to heroku's servers.
git add .
git commit -m "Initial commit."
git push heroku master
And then in the browser ensure that you see "Hello world from srcmake!".
heroku open
We went through this section quickly, but I did a whole video on it in Part D of the Java Series, so be sure to watch the video on it if you're confused. 

Expand The Project For Our Necessary Endpoints

We want our URLs to look like: www.srcmake.com/v1/fruits/add. We need paths for /v1/fruits/add, /v1/fruits/subtract, and /v1/fruits/check. Luckily, this is easy to implement using Spring. We'll add for functions that handle each of these endpoints, as well as the specific HTTP methods that the endpoints go with. (This webpage is a really really good resource for seeing how to add paths using Spring's request mapping.)

In src/main/java/com/example/myapp, change the contents of "DemoApplication.java" to the following:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.*;

@Controller
@SpringBootApplication
public class DemoApplication 
        {
        ////////////////////////////////////////////////
    @RequestMapping("/")
    @ResponseBody
    String home()       
        {
        return "Hello World from srcmake!";
        }
        ////////////////////////////////////////////////


        ////////////////////////////////////////////////
        // /v1/fruits/add
        @RequestMapping(value = "/v1/fruits/add", method=RequestMethod.POST)
    @ResponseBody
    String FruitsAdd(@RequestParam("fruitname") String fruitname, @RequestParam("quantity") Integer quantity)
        {
        // Start the response to return to the API user.
        String response = "Called /v1/fruits/add.\n";
        response += "You want to add " + Integer.toString(quantity) + " " + fruitname + "'s.";

        // TODO: ADD CODE TO UPDATE THE DATABASE HERE.
        
        return response;
        }
        ////////////////////////////////////////////////


        ////////////////////////////////////////////////
        // /v1/fruits/subtract    
        @RequestMapping(value = "/v1/fruits/subtract", method=RequestMethod.POST)
    @ResponseBody
    String FruitsSubtract()     
        {
        // TODO: ADD CODE TO ACCEPT PARAMETERS HERE.
        // TODO: ADD CODE TO UPDATE THE DATABASE HERE.

        return "Called fruits/subtract";
        }
        ////////////////////////////////////////////////


        ////////////////////////////////////////////////
        // /v1/fruits/check
    @RequestMapping(value = "/v1/fruits/check", method=RequestMethod.GET)
    @ResponseBody
    String FruitsCheck()        
        {
        // TODO: ADD CODE TO ACCEPT PARAMETERS HERE.
        // TODO: ADD CODE TO QUERY THE DATABASE HERE.

        String response = "Called /v1/fruits/check.";
        return response;
        }
        ////////////////////////////////////////////////


        ////////////////////////////////////////////////
        // MAIN
    public static void main(String[] args) 
        {
        SpringApplication.run(DemoApplication.class, args);
        }
        ////////////////////////////////////////////////
        }
(The indentation looks really weird. Sorry.)

We added three functions, one for each of the endpoints that we care about. They return placeholder strings for now. 
Our project is actually complete right now. For now.

Testing The Code

We need maven to test the code, so if you haven't installed it yet, go to the Java series page and scroll down to Video A: Building with Maven. Follow the instructions to install Maven.
In the root of our project directory (make sure to go back to our project if you had to install maven), run the following command.
mvn spring-boot:run
The terminal should be acting as a server now, so we can test our code using postman (or the web browser). Go to the following URLs to check each of our endpoints:

localhost:8080/
localhost:8080/v1/fruits/check
localhost:8080/v1/fruits/add?fruitname=apple&quantity=50
​localhost:8080/v1/fruits/subtract
Make sure the last two commands are POST. (Meaning you need to use Postman, not just the web browser. If you don't know how to use Postman, see this article.)

​Try the /add endpoint without giving a fruitname or quantity and see what happens. Currently, we'd give an error message, which is VERY bad programming. We'll handle that in a future video. 
Don't forget to push the code to Heroku. (If you want too.)
git add .
git commit -m "Added fruits endpoints."
git push heroku master

Conclusion

Okay, so in this blog post we took the starter API code that we we made in the Java series, and we start by git cloning it locally to our computer as well as pushing it to Heroku. (Which is good for testing.) 

The main thing that we did was add a few endpoints by creating extra functions. We also saw how to get our server running so that we could test those endpoints using postman, with maven as our build tool. 

What we did was very very basic, but it's the building block for writing a Java API.

However, there's a TON of stuff that we didn't do. We didn't handle when the user forgets to give a parameter, which means giving a default parameter type. We didn't handle different response codes. We didn't move our functions to another file for cleanliness. We also didn't actually code the database functionality or write anything useful for our endpoints (although, that's more "Java" than it is "API").
In another blog post, we'll go over the advanced topics of building a Java API. To be 100% honest, building the API in Node is sort of easier, so before going too deep with Java, give the Node tutorial a shot. However, we'll still trek deeper with Java APIs in the next blog post.
Here's the youtube video where I go over the steps in this article:
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels. 

Twitter: @srcmake
Discord: srcmake#3644
Youtube: srcmake
Twitch: www.twitch.tv/srcmake
​Github: srcmake
References
1. devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku
2. www.baeldung.com/spring-requestmapping

Comments are closed.

    Author

    Hi, I'm srcmake. I play video games and develop software. 

    Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
    Metamask tip button
    License: All code and instructions are provided under the MIT License.

    Discord

    Chat with me.


    Youtube

    Watch my videos.


    Twitter

    Get the latest news.


    Twitch

    See the me code live.


    Github

    My latest projects.

Powered by Create your own unique website with customizable templates.