API Request and Response Part#1

Have you ever come across the word API and wondered what it really means? Maybe you tried reading about it and got confused by the dreadful technical terms. Here, we will be going through what API really means and how it works. This topic will be divided into two parts for better clarification. First part will go through REST APIs and JSON APIs (don’t worry, we’ll go through that) and in second part, we’ll try implementing APIs in Laravel.

What in the name of sorcery API is?

API stands for Application Programming Interface. As the name suggests, API means a small interface of your application which is accessible from anywhere. You allow the user to access your data without knowing the database details. In simpler terms, you define some endpoints where anyone can make a request and get the details.

Most of the times,we create an API for our mobile application to sync the data along with the web version or website. Here we can say API is an endpoint between mobile device and database server.API maybe used to handle public or private requests. Now, what is public request and what is private request? Public request means anyone from the world can make request and get the results without any barrier or security. For data security concerns, its not proper way to make APIs publicly accessible. To avoid this you can add an authentication barrier for API. By using this only authenticated requests get proper result.

Now you might have a question like if I allow users to register into my application from mobile and somehow,they request the API without registration. Can we add authentication now? In this kind of public request, you have to use RefreshToken & AccessToken. Now this will work similarly as authentication for that request. This token will expire after sometime and you have to regenerate a new access token by passing your refresh token key. You can set time limit as needed between 5 mins to 30 mins.

What is RESTAPI?

REST stands for REpresentational State Transfer means, you represent your entity to the end user with only required details only. You do not allow everyone to access your database.It’s stateless, like you can't maintain sessions for each request like we did on the web. Each API contains its own authentication key to access the users or to maintain the virtual state. Plus point about APIs are you can design endpoints in a way that end user won't know that this is actual server, proxy server or load balancer.

Uniform interface like, you can identify the resource through URL or endpoint. We will learn through an example, there list of posts on my website and I want to make APIs to get list, add, edit and delete the posts. Now I define APIs endpoint as per my URL behavior. You can design endpoint like,

  • www.domain.com/api/posts : List of all posts.
  • www.domain.com/api/post/12 : Get details of post with ID of 12.
  • www.domain.com/api/post/create : You can create new posts.
  • www.domain.com/api/post/edit/12 : Edit post with ID of 12.
  • www.domain.com/api/post/delete/12 : Delete post with ID of 12.

REST has no preferred URL patterns and it’s completely up to you how you pass set your endpoint.It’s not compulsory to a JSON.

APIs Request and Responsive

It’s very important to know about best practices for create an endpoint or APIs for your system. First, let's begin with HTTP request.

Try to use proper HTTP method to for API request. GET method to fetch records and for listing. POST method to add new details to database. PUT/PATCH method to update records. DELETE to remove record. Here are few examples which helps you to get better idea.

  • GET : www.domain.com/api/posts : Fetch all records.
  • GET : www.domain.com/api/post/12 : Fetch single records.
  • POST : www.domain.com/api/post/create : Add new records.
  • PUT/PATCH : www.domain.com/api/post/edit/12 : Update record.
  • DELETE : www.domain.com/api/post/delete/12 : Delete record.

This is all about the request details. Now let’s see how to set proper response of the request. To understand, how to create response we take an example of posts where users can post an article and each article has one author and banner image. Each response is divided in mostly 5 parts and all parts are optional. All 5 parts are mentioned below and we will look in every part (keys) deeply.

  • data : here you can pass the actual data.
  • includes : pass related data.
  • errors : if any error occur.
  • meta and links: optional details like messages and links.
  • version : current API request/response version.

Let's break down all the parts (keys) of response in deep with example.

Data

It maybe a single object or array of an object. You add actual data of your website. Here I share details of posts from my database. Data is a core data of your API.

{
    " data ":
    {
        "type": "posts",
        "id": 12,
        "attribute":
        {
            "title": "This is my post's title",
            "description": "All description of post goeshere",
        },
        "relations":
        {
            "author":
            {
                "type": "author",
                "id": 1,
            }
        },
        "links":
        {
            "banner": " https://www.domain.com/images/posts/post-banner.jpg ",
        },
        "meta":
        {
            "views": 500,
            "comments": 100,
            "reports": 10,
        }
    },
}

Includes

This is used to get data of relations, in our case the author. You can say like, details of relations in meta must include this section.

{
    " includes ":
    {
        "type": "authors",
        "id": 1,
        "attribute":
        {
            "first_name": "John",
            "last_name": "Smith",
            "email": "[email protected]",
        },
        "links":
        {
            "profile": " https://www.domain.com/images/profile/jonh-smith.jpg ",
        },
        "meta":
        {
            "created": "29 August, 2020",
            "last_edited": "30 August, 2020",
        }
    },
}

errors

This key is use to through errors like 404 or server error. You can access details about error using this key. Its maybe single object or array of objects. Important think, pass proper HTTP code with this key, don't use 200 if you pass this key.

{
    "errors":
    {
        "status": 503,
        "code": "UNDER_MAINTENANCE",
        "title": "Under Maintenance",
        "message": "Currently we are updating server details forbetter performance, pleasetry aftersome time",
        "source":
        {
            // USED IF ERROR COME FOR FIELD LIKE "EMAIL"
        },
        "meta":
        {
            "support": " [email protected] ",
        }
    },
}

Meta and Links

Meta and links are optional keys of response. Sometime its useful to pass trivial details. I mostly suggest to use meta key to pass extra details like response version, request version, messages, count etc. Links key is use to share additional link for pagination. Mostly I use this to share pagination URL. You can this key use to share dynamic url for share profile or refer and earn feature.

{
    "meta":
    { // This is extra information for overall response like
        message "message": "Post's details retrieve successfully!",
    },
    "links":
    {
        // Extra links for sharing or pagination
        "sharing": "your-deeplink-or-share-url",
    },
}

Version

Version key is use to pass current version of response. You can pass current version, new version and updated on date. This keys is use if you update APIs and want to inform. To be very honest, I didn't use this key yet in my projects.

This key is important to share current version of API and update version of API. I mostly pass versioning details in meta.

{
    "version":
    {
        "current_version": "1.0",
        "new_version": "1.2",
        "updated_on": "2020-08-29",
    },
}

There is no rule that you must follow these details. Its completely up to you. This post will help you to define standard request and response of your APIs. For every response you have to use proper HTTP codes like, 200, 201, 404, 500 etc.

Hands on API development

That’s it for this post. This is a short summary of this blog.

  1. We learnt about what is API and use of APIs.
  2. How to create standard request, use HTTP request code for each request.
  3. How to define your API response with example. Use proper HTTP response code as per response need.

In the next part, we’ll go in deep about how to implement APIs with Laravel Eloquent Resources.


Leave a Reply

Your email address will not be published. Required fields are marked *