DEV Community

Cover image for Introduction to APIs
Vaishnavi Patil
Vaishnavi Patil

Posted on • Edited on

Introduction to APIs

API stands for Application Programming Interface.You may use APIs to request access to another server's resources or you may use your own APIs to automate certain tasks.A Browser API can extend the functionality of a web browser. A Server API can extend the functionality of a web server.

What is API used for in web development

API is the acronym for Application Programming Interface, which 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.

How to use an API?

The steps to implement a new API include:

Obtaining an API key. This is done by creating a verified account with the API provider.
Set up an HTTP API client. This tool allows you to structure API requests easily using the API keys received.
If you don’t have an API client, you can try to structure the request yourself in your browser by referring to the API documentation.
Once you are comfortable with the new API syntax, you can start using it in your code.

Types of API

There are 4 main types of APIs(Application Programming Interface) by availability/release policies-

1.Open APIs (Public APIs)- Publicly available to developers and other users with minimal restriction. They may require registration, use of an API Key or OAuth, or maybe completely open. They focus on external users, to access data or services.

2.Partner APIs- allows you as a partner to perform all the GET operations that you do in your partner store. partner API is built using REST principles. This ensures predicatable URLs that make it easy to write and retrieve data related to your partner store. This API follows HTTP rules.

3.Internal APIs (private APIs)- Provide access to sensitive resourses within an organization's software system. They simplify the process of linking back-end systems or data between the multitude of applications that control internal operations.

4.Composite APIs- Design approach to batch API requests sequentially into a single API call. Rather than multiple round trips to a server, a client can make one API request with a chain of calls and receive one response.

Image description

Different types of API Protocols

1.SOAP
2.REST
3.JSON-RPC
4.gRPC
5.GraphQL
6.XML-RPC
7.Apache Thrift

Difference between GraphQL and REST API

Image description

GraphQL

GraphQL is a query language and server-side runtime for application programming interfaces(APIs) that prioritizes giving clients exactly the data they request and no more. GraphQL is designed to make APIs fast, flexible, and developer-friendly.

Features of GraphQL

Here are important features of GraphQL:

  • It is statically typed, so you do not need to define variable before using it.
  • GraphQL can decouple frontend from backend.
  • No over or under fetching of data.
  • It is language and HTTP agnostic.
  • Documentation of GraqphQL comes with no extra cost.
  • It helps you to save bandwidth.

Fetching Remote Data

Assume that a mobile or web app wants to access data from a server that displays the blog author information. The app is supposed to display the author’s name, the blog posts written by the author, and the three most recent blog topics written by him/her. Let’s give an abstract level review on how to fetch this data in REST vs GraphQL.

fetch('https://learnwithjason.dev/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: `
        query GetLearnWithJasonEpisodes($now: DateTime!) {
          allEpisode(limit: 10, sort: {date: ASC}, where: {date: {gte: $now}}) {
            date
            title
            guest {
              name
              twitter
            }
            description
          }
        }
      `,
    variables: {
      now: new Date().toISOString(),
    },
  }),
})
  .then((res) => res.json())
  .then((result) => console.log(result));
Enter fullscreen mode Exit fullscreen mode

Image description

GraphQL Query Request

In this post, we discussed how you can use HTTP GET and POST methods to send GraphQL requests. We also looked at some of the nuances and limitations of each approach.

Image description

Rest API

When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text. JSON is the most generally popular file format to use because, despite its name, it’s language-agnostic, as well as readable by both humans and machines.

Fetching Remote Data

APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.

In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node.js.

fetch("/add", {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            a: parseInt(a),
            b: parseInt(b)
        })
    })
    .then(res => res.json())
    .then(data => {
        const {
            result
        } = data;
        document.querySelector(
            ".result"
        ).innerText = `The sum is: ${result}`;
    })
    .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

Image description

REST Request

REST requires that a client make a request to the server in order to retrieve or modify data on the server. A request generally consists of: an HTTP verb, which defines what kind of operation to perform. a header, which allows the client to pass along information about the request.

Image description

Top comments (0)