Beginners Guide To Understanding REST API - Tech Projects/Documentations
image

Beginners Guide To Understanding REST API

Introduction to REST API:

Case study: Android applications built with java

Author: Eze-Odikwa Tochukwu Jed

Introduction:

API is a term that you will see in programing languages everywhere. It is really about clients and servers. An API stands for Application Programming Interface. It simply means that there is a server somewhere providing data to the client. By now we are all used to the instant connectivity we experience over the internet like never before and part of what to thank for this are APIs. An API is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.

Over the years, what an API is has often described any sort of generic connectivity interface to an application. More recently, however, the modern API has taken on some characteristics that make them extraordinarily valuable and useful:

  • Modern APIs adhere to standards (typically HTTP and REST), that are developer-friendly, easily accessible and understood broadly
  • They are treated more like products than code. They are designed for consumption for specific audiences (e.g., mobile developers), they are documented, and they are versioned in a way that users can have certain expectations of its maintenance and lifecycle.
  • Because they are much more standardized, they have a much stronger discipline for security and governance, as well as monitored and managed for performance and scale
  • As any other piece of productized software, the modern API has its own software development lifecycle (SDLC) of designing, testing, building, managing, and versioning.  Also, modern APIs are well documented for consumption and versioning.

REST API: Also referred to as RESTful API Representational state transfer, is an architectural style for an Application Programming Interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to reading, updating, creating and deleting operations. REST technology is generally preferred over other similar technologies. This tends to be the case because REST uses less bandwidth, making it more suitable for efficient internet usage. RESTful APIs can also be built with programming languages such as JavaScript or Python.

Copyright@ flaticons.com

To understand REST, we need to review some key terms first:

  • A client is the person or program using the API. The client makes requests to the API in order to retrieve some information or change something within the application. Your web browser is a client — it interacts with APIs different websites to get page content from them. The requested info is sent back to your browser and displayed on your screen.
  • A resource is any piece of information that the API can provide the client. For instance, a resource in Facebook’s API could be a user, a page, a photo, or a post. Each resource has a unique name, called the resource identifier.
  • A server is used by the application that receives client requests, and contains resources that the client wants. The server has an API to interact with clients without giving them direct access to content stored in its database.

Like all requests to a REST API, these requests contains certain pieces of information:

GET is the HTTP method. This specifies the action the client wants to make on the resource. The four basic HTTP requests a client can make are:

  • GET: To retrieve a resource.
  • POST: To create a new resource.
  • PUT: To edit or update an existing resource.
  • DELETE: To delete a resource.

https://… is a URL. A URL contains the uniform resource identifier, or URI, which specifies the target resource. URL is also called an endpoint because it is the location where the API actually interacts with the client.

After receiving and validating requests, the host returns information about the target resource. Usually, the information is sent back in a format called JSON, which stands for JavaScript Object Notation. JSON lays out all the contents of a resource in a lightweight format that humans can easily read. XML can also be used but most developers prefer JSON because of how easy it is to implement.

So what is JSON? JavaScript Object Notation, it is a lightweight format for storing and transporting data and often used when data is sent from a server to a webpage or webapp, now you see why it used in REST API. JSON has wide range of uses and implementations. In fact throughout your software engineering carrier you will definitely end up implementing JSON a lot in your software applications especially when it comes to collecting analytical data, crash logs and the likes.  

JSON example:

{
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

JSON Syntax Rules:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Data – A Name and a Value: JSON data is written as name/value pairs, just like JavaScript object properties. A name/value pair consists of a field name (in double quotes), followed by a colon, and followed by a value:

"firstName":"John"

JSON Objects: JSON objects are written inside curly braces. Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John", "lastName":"Doe"}

JSON Arrays: JSON arrays are written inside square brackets. Just like in JavaScript, an array can contain objects:

"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]

In the example above, the object “employees” is an array. It contains three objects. Each object is a record of a person (with a first name and a last name).

Converting a JSON Text to a JavaScript Object: A common use of JSON is to read data from a web server, and display the data in a web page. For simplicity, this can be demonstrated using a string as input. First, create a JavaScript string containing JSON syntax:

var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:

var obj = JSON.parse(text);

Finally, use the new JavaScript object in your page:

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

Many APIs require an API key to use. An API key is a unique string of characters that an API provider gives to a developer to authorize access to their API. API keys are often sent with client requests to identify the client to the server. Keep your API key(s) private. If your key falls into the wrong hands, it could be used to do some not-so-good things seemingly on your behalf.

Accept and respond with JSON: REST APIs should accept JSON for request payload and also send responses to JSON. JSON is the standard for transferring data. Almost every networked technology can use it: JavaScript has built-in methods to encode and decode JSON either through the Fetch API or another HTTP client. Server-side technologies have libraries that can decode JSON without doing much work.

To make sure that when our REST API app responds with JSON that clients interpret it as such, we should set Content-Type in the response header to application/json after the request is made. Many server-side app frameworks set the response header automatically. Some HTTP clients look at the Content-Type response header and parse the data according to that format.

Let’s take a look at an example API that accepts JSON payloads. This example will use the express back end framework for Node.js. We can use the body-parser middleware to parse the JSON request body, and then we can call the Res.json method with the object that we want to return as the JSON response as follows:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());

app.post('/', (req, res) => {
  res.json(req.body);
});

app.listen(3000, () => console.log('server started'));

bodyParser.json() parses the JSON request body string into a JavaScript object and then assigns it to the req.body object. Set the Content-Type header in the response to application/json; charset=utf-8 without any changes. The method above applies to most other back end frameworks.

We would expand on this in future topics on REST APIs.

Why use REST APIs? The REST framework was introduced by computer scientist Roy Fielding in 2000, and today it shapes how we view, modify, and transfer content online. Many of the most popular web and cloud companies use REST APIs for their applications, including Facebook, YouTube, Twitter, Google and this website you are reading on *winks*.

REST API client application example source code: This is to showcase a simple REST API client application example built with java programming language. The app has a login page and uses basic authentication for verifying login credentials. Download the source code by clicking HERE.

Sample REST API android application

Note: Configuring a server and creating a REST API is outside the scope of what is being shown. However basic knowledge of PHP is required as you will have to host a short PHP file that will verify authentication using this example app.  

The app relies on a couple of dependencies, using the com.orellly.servlet package for encoding REST API requests in base 64 format. In another dependency it has a server running a REST API for the app to communicate with.

Launch android studio and follow these steps:

Step 1: Create a new android studio project select empty activity name your application i will name mine sampleRESTAPI with package name of com.tochycomputerservices.sample select the desired SDK version and hit create.

Step 2: Copy and paste the following code into your AndroidManifest.xml file this enables your app to communicate to the network.

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Step 3: Download the source code by clicking HERE copy and replace the files into your android studio project. Click refactor if you get a pop up. Open the original files in VS code to compare some things in detail.

Step 4: Copy and paste this PHP code into a new .PHP file. You can create one using visual studio. I named mine rest.php.

<?php
# Get the username and password from the headers
$username = $_SERVER["PHP_AUTH_USER"];
$password = $_SERVER["PHP_AUTH_PW"];

#Check if the credentials are valid.
if ($username == "username" && $password == "password"){
    echo "true";
}
else{
    echo "false";
}

Also note: For the PHP file you must have apache PHP installed on your computer for this file to work. Place it wherever your web server retrieves files that are facing the network. Download XAMP for windows or MAMP for Mac if you don’t have a server. For Linux get Apache and PHP from your distributor’s repository. You can also host this PHP file if you have ready access to a domain and server hosting as you will be needing the domain web address later in this practical however i won’t be hosting any PHP file here as what I am doing is very similar to what is on the backend of this very website.

Explanation of key terms:

The source code itself is self-explanatory however I will want to make a few things clear.

1) If the HTTP method is either POST or PUT you will be sending output to the server for writing purposes. you will get your headers, retrieve your inputs and then disconnect our connection. Citing this code snippet below in the source code.

if (httpMethod.equals("POST") || httpMethod.equals("PUT")) {

                payload = getPayloadAsString();

                connection.setDoInput(true);
                connection.setDoOutput(true);

                try {
                    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                    writer.write(payload);

                    headerFields = connection.getHeaderFields();

                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        outputStringBuilder.append(line);
                    }
                } catch (Exception ex) {}
                connection.disconnect();
            }
            else {
                InputStream content = (InputStream) connection.getInputStream();

                headerFields = connection.getHeaderFields();

2) If you are testing on a local machine you can get your IP address by typing: ipconfig and replacing your IP address in the base URL, else you could use the domain URL of your test server/host. Also make sure you are pointing to the rest.php file that you created using the code sample in this blog post.

References:

stackoverflow.com/questions/671118/what-is-restful-programming

stackoverflow.com/2020/03/02/best-practices-for-rest-api-design/

github.com/tochyodikwa/REST-API-practice

servlets.com/

leave your comment


Your email address will not be published.

Uploading