API’s are wonderful tools, and learning why you use them, and how to create them is incredibly valuable. There’s thousands of APIs that are exposed to the public for use. From GitHub, to Stripe or Google Calendar APIs allow you to access and utilize other systems. This tutorial is going to teach you how to use, and make your own API so that you can take advantage of the power that REST provides.

What are APIs?

The best example I can give for a use case for an API is for a simple request to a database:

Let’s say you have a database on a server. Let’s say you have a table of users. It has username, email, phone numbers and password hashes stored in it. Now let’s say another application wants to access that information. But maybe you don’t want to provide them with the raw password hash.

{
"error": "Invalid Credentials"
}
{
"username": "matted",
"email": "matted@cs.house",
"phone": 5555555555
}

What is RESTful?

From codecademy: In the REST architectural style, the implementation of the client and the implementation of the server can be done independently without each knowing about the other. This means that the code on the client side can be changed at any time without affecting the operation of the server, and the code on the server side can be changed without affecting the operation of the client.

  • POST — update a specific resource (by id)
  • PUT — create a new resource
  • DELETE — remove a specific resource by id

Paths

First thing we should go over, is how to structure an API. RESTful APIs are accessed generally through simple web routes. Think of something like google.com/ and google.com/search. You're already likely familiar with the fact that google.com/ is the route to get the main page.

Root

/ is an example of the "root" path of the API. It's what's loaded when you go to either google.com or google.com/.

Routes

/search is the route that exists in the path google.com/search. When you write routes, there is no limit to the path, /this/is/a/long/path/which/is/valid. You should however, try and keep your routes short and simple. Routes should be easily understood, and generally memorable so that people are able to type it in, or understand what information will be provided simply from the URL.

Parameters

Parameters are a huge part of APIs. In order for a lot of them to be useful, there needs to be an ability to pass data. You can do this by using parameters.

  • q: api
  • gs_l: psy-ab.3..35i39k1l2j0i131k1j0j0i20i264k1j0i131k1j0i20i264k1j0i131k1j0l2.3075.3336.0.4076.3.3.0.0.0.0.81.215.3.3.0….0…1c.1.64.psy-ab..1.3.215…0i131i20i264k1.0._czjqWn7yUE

Status Codes

Understanding Status codes is imperative to being able to understand what to do with the data returned by a restful API. What a status code does, is tell you whether or not a request was successful or not, and describes the result before you even read the data returned.

  • 2xx: Success.
  • 3xx: Redirection.
  • 4xx: Client errors.
  • 5xx: Server errors.

Make your Own

To follow along, clone the example repo and checkout the language/framework of your choice.

git clone https://github.com/devinmatte/Your-First-API.git
git checkout [branch]
  • Java with Spring: java_spring
  • PHP with Slim: php_slim
  • Node with Express node_express

Tools

You may at many points want to test your API. A good tool for that would be Postman. Allows for you to make GET, POST, PUT, and DELETE requests easily and read the response.

Getting started

Let’s start with simply making a root route that returns “Hello World!” to the body of the response.

Python/Flask

  • First run pip install -r requirements.txt
  • Make sure you’re using Python3, you may need to use pip3 instead of pip on some systems.
  • Edit __init__.py and add the following route, then run app.py to test.
@app.route("/", methods=["GET"])
def root():
return "Hello World!"

Java/Spring

  • I recommend using an IDE for all Java Development
  • I also recommend using Intellij
  • Add build.gradle and pom.xml to the gradle/mavenportions of your IDE
  • Make sure to mark src as the sources directory
  • Run Application.java to run/test your application
@RequestMapping("/") 
public String root() {
return "Hello World!";
}

PHP/Slim

  • First run composer install
  • If you don’t have composer, install it
  • Edit routes.php and add the following route, then run php -S localhost:3000 -t index.php to test.
$app->get('/', function (Request $request, Response $response) {
return $response->write("Hello World!");
});

Node/Express

  • First run npm install
  • If you don’t have node, install it
  • Edit app.js and add the following route, then run node app.js to test.
app.get('/', (req, res) => res.send('Hello World!'));

Multiple Request Types

Not every request in an API is GET in most cases. Often an API allows for you to make requests to change the underlying data in the system. In order to do this, you’re going to want to take advantage of POST, PUT and DELETE. Doing so in each framework is fairly easy to define.

Python/Flask

Java/Spring

PHP/Slim

Node/Express

Using Status Codes

HTTP requests are made up of two parts, the payload, and the status code. The status code tells whether a request was successful, or failed. It also allows for you handle the results of requests based on the code that it provides. Status codes are generally pretty consistent, so if you’re confused what code to return, just reference the spec.

Python/Flask

# Return a 205 
@app.route("/success", methods=["GET"])
def return_success():
return "This will return a 205 Status Code", 205
# Return a 404
@app.route("/fail", methods=["GET"])
def return_fail():
return "This will return a 404 Status Code", 404

Java/Spring

// Return a 205 
@RequestMapping(value = "/success", method = RequestMethod.GET)
public ResponseEntity returnSuccess() {
return ResponseEntity.status(205).body("This will return a 205 Status Code");
}
// Return a 404
@RequestMapping(value = "/fail", method = RequestMethod.GET)
public ResponseEntity returnFail() {
return ResponseEntity.status(404).body("This will return a 404 Status Code");
}

PHP/Slim

// Return a 205 
$app->get('/success', function (Request $request, Response $response) {
return $response->write("This will return a 205 Status Code")->withStatus(205);
});
// Return a 404
$app->get('/fail', function (Request $request, Response $response) {
return $response->write("This will return a 404 Status Code")->withStatus(404);
});

Node/Express

// Return a 205 
app.get('/success', function (req, res) {
res.status(205);
res.send('This will return a 205 Status Code');
});
// Return a 404
app.get('/fail', function (req, res) {
res.status(404);
res.send('This will return a 404 Status Code');
});

Get Data to Return

Often APIs are stateless, meaning that they get the data from somewhere. You aren’t going to be storing data in data structures as your long term storage. Because of that you’ll often interact with Databases. Each language works really well with a number of frameworks. I will recommend some good ORMs for each language below, but you should do your research to find one that works for your use case.

Python/Flask

Java/Spring

PHP/Slim

Node/Express

Continue Learning

If you want to learn more about APIs or any of these frameworks, there are plenty of good resources available.

Frameworks

Software Engineering Student at Rochester Institute of Technology with a focus on Full Stack Web Development and DevOps