Most Frequently asked api Interview Questions and Answers

author image Hirely
at 03 Jan, 2025

Question: What is JSON and XML, and how are they used in APIs?

Answer:

JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two popular data formats used for exchanging information between a client and server in web APIs. Both serve as a medium for representing data structures in a readable format that can be easily parsed by machines, but they differ in structure, readability, and use cases.


1. JSON (JavaScript Object Notation)

What is JSON?

  • JSON is a lightweight, text-based data format that is easy to read and write for humans and easy to parse and generate for machines.
  • It is commonly used for transmitting data in web applications, especially for APIs, and is widely supported by programming languages, including JavaScript, Python, Java, C#, and many others.

JSON Syntax:

JSON data is structured as key-value pairs, similar to how objects are represented in JavaScript. Here’s an example of a JSON object:

{
  "name": "John Doe",
  "age": 30,
  "isActive": true,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "zip": "12345"
  },
  "phoneNumbers": [
    { "type": "home", "number": "123-456-7890" },
    { "type": "work", "number": "987-654-3210" }
  ]
}
  • Key-value pairs: Data is represented as a combination of keys (or names) and values. Keys are always strings, and values can be strings, numbers, booleans, arrays, or other objects.
  • Objects: Represented by curly braces {}. They can contain multiple key-value pairs.
  • Arrays: Represented by square brackets []. Arrays can contain multiple values, such as strings, numbers, objects, or other arrays.

How is JSON used in APIs?

  • Request and Response Format: JSON is commonly used in APIs as the format for both sending requests to a server and receiving responses. For example, a client might send a JSON object as part of a POST request to create a new user, and the server will respond with another JSON object containing the result of that operation.
  • RESTful APIs: JSON is the most common format used in REST APIs due to its lightweight nature and ease of parsing.
  • JavaScript: JSON is natively supported in JavaScript, making it a natural choice for APIs interacting with web applications.

2. XML (eXtensible Markup Language)

What is XML?

  • XML is a markup language designed to store and transport data in a format that is both human-readable and machine-readable. Unlike JSON, XML uses a hierarchical structure with tags to define elements and their relationships.
  • It is more verbose and less lightweight compared to JSON but was widely used in APIs for a long time, especially in SOAP (Simple Object Access Protocol) web services.

XML Syntax:

XML uses a set of custom tags to define data. Here’s an example of the same data structure represented in XML:

<person>
  <name>John Doe</name>
  <age>30</age>
  <isActive>true</isActive>
  <address>
    <street>123 Main St</street>
    <city>Anytown</city>
    <zip>12345</zip>
  </address>
  <phoneNumbers>
    <phoneNumber type="home">123-456-7890</phoneNumber>
    <phoneNumber type="work">987-654-3210</phoneNumber>
  </phoneNumbers>
</person>
  • Tags: XML uses tags (e.g., <name>, <address>, etc.) to define the structure of the data. Tags are nested to indicate relationships between elements.
  • Attributes: Elements can have attributes (e.g., type="home" in <phoneNumber>).
  • Hierarchy: XML data is represented in a tree-like structure, where elements can contain other elements (child elements).

How is XML used in APIs?

  • Request and Response Format: Similar to JSON, XML can be used to send and receive data in web services. XML data is often used in legacy systems, SOAP APIs, or when there’s a need for more complex data descriptions.
  • SOAP APIs: SOAP (Simple Object Access Protocol) APIs typically use XML as the format for both the request and response. SOAP is a protocol that defines rules for exchanging structured information, and XML is the format used to structure those exchanges.
  • Document-Oriented Services: XML is often used in document-oriented services where data needs to be more self-descriptive with tags and attributes, which makes it suitable for more complex documents.

3. Comparison of JSON and XML

FeatureJSONXML
StructureKey-value pairsTags (elements) and attributes
FormatLightweight, compactMore verbose, heavy
ReadabilityEasier to read and write for humansMore difficult to read and write
Data SizeSmaller, more compactLarger, due to tags and verbosity
ParsingFaster to parse (less overhead)Slower to parse due to more complexity
SupportNative support in JavaScriptSupported in many languages but not as natively integrated as JSON
Data TypesSupports basic types (string, number, array, boolean, null, object)Supports complex types (can represent metadata, data structure, and types through attributes)
SchemaNo strict schema (flexible)Can be schema-based (e.g., XML Schema)
Use CasesREST APIs, Web Applications, Mobile AppsSOAP APIs, Complex Data Interchange, Legacy Systems
NamespacesNot natively supported (but can be managed)Strong support for namespaces to avoid tag conflicts
Error HandlingEasier to handle errors (less verbose)Can be more complex due to verbosity

4. How JSON and XML Are Used in APIs

  • Request and Response: Both formats are commonly used to exchange data in web services. Clients (e.g., browsers, mobile apps, or other APIs) send requests, often in JSON or XML format, to the server. The server processes the request and sends back a response, usually in the same format (JSON or XML).

  • RESTful APIs and JSON:

    • JSON is the preferred format for REST APIs due to its simplicity, smaller size, and ease of use with JavaScript.
    • Example (Request in JSON format):
      {
        "username": "johndoe",
        "password": "password123"
      }
    • Example (Response in JSON format):
      {
        "status": "success",
        "message": "Login successful",
        "data": {
          "userId": 1,
          "username": "johndoe"
        }
      }
  • SOAP APIs and XML:

    • XML is the primary format used by SOAP web services. A SOAP request or response is typically wrapped in an XML envelope that contains headers and the body.
    • Example (SOAP Request in XML format):
      <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservice">
        <soapenv:Header/>
        <soapenv:Body>
          <web:Login>
            <username>johndoe</username>
            <password>password123</password>
          </web:Login>
        </soapenv:Body>
      </soapenv:Envelope>

5. Conclusion:

  • JSON is the preferred choice for most modern APIs due to its simplicity, small size, and ease of integration with JavaScript-based applications. It is widely used in RESTful APIs and web services.
  • XML is used in APIs where more complex data structures, namespaces, or document-centric data representations are needed, such as in SOAP APIs or legacy systems. It is more verbose and slower to parse compared to JSON, but it offers robust support for complex data structures and metadata.

In practice, many modern APIs favor JSON due to its compactness and ease of use, but XML is still used in specific cases, particularly in enterprise or legacy environments.

Question: What is Cross-Origin Resource Sharing (CORS) and why is it important in APIs?

Answer:

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that controls how web pages from one domain can request resources from a different domain. It is particularly important for APIs that are accessed by client-side web applications hosted on a different domain from the API server. CORS is a mechanism that allows or restricts cross-origin HTTP requests made by web browsers.


1. What is Cross-Origin Resource Sharing (CORS)?

  • Cross-Origin refers to a request for a resource (such as an API endpoint, image, script, or stylesheet) where the resource is hosted on a different domain, protocol, or port than the one the web page is served from. For example, if your website (front-end) is hosted at https://example.com and your API is hosted at https://api.example.com, the request from your website to the API is considered a “cross-origin request.”

  • Resource Sharing is the ability for one origin (domain, protocol, port) to access resources (data) from another origin. CORS is a protocol that governs how browsers allow such resource sharing.

CORS is designed to prevent malicious websites (attacker websites) from reading sensitive data from other sites or interacting with other web applications on behalf of the user without their consent.


2. Why is CORS Important in APIs?

CORS is important for the following reasons:

  • Security: By default, web browsers block web pages from making requests to a different domain (cross-origin requests). This is done to prevent malicious scripts running in the browser from accessing resources on other websites without permission (cross-site request forgery or cross-site scripting attacks).

  • Allowing Safe Cross-Domain Requests: For legitimate purposes, such as an API on one domain and a client-side application (e.g., a web front-end) on another domain, CORS allows these applications to securely interact with each other. For example, a React or Angular web app hosted on https://example.com may need to make API requests to https://api.example.com. CORS provides a mechanism to allow these cross-origin requests while ensuring that unauthorized or malicious websites cannot abuse the resources.

  • API Accessibility: CORS allows developers to control which domains are permitted to access the API. By defining CORS policies, API owners can restrict access to trusted domains or resources, reducing potential security risks.


3. How Does CORS Work?

When a web browser makes a cross-origin request (e.g., an AJAX request from a front-end application to an API), the browser sends an HTTP request with special headers that indicate it’s a cross-origin request. The most important header in this context is the Origin header, which indicates the origin of the calling script.

1. Preflight Request:

For certain types of requests (e.g., methods like PUT, DELETE, or custom headers), the browser first sends a preflight request using the HTTP OPTIONS method to check whether the server allows cross-origin requests. The preflight request contains the Origin header and other headers like Access-Control-Request-Method and Access-Control-Request-Headers to ask for permission from the server to perform the actual request.

Example of a preflight request:

OPTIONS /api/data HTTP/1.1
Host: api.example.com
Origin: https://example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

2. Server Response:

The server responds with the CORS headers to indicate whether the request is allowed. These headers include:

  • Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource. It can be a specific domain (e.g., https://example.com) or a wildcard (*) to allow all domains.
  • Access-Control-Allow-Methods: Specifies which HTTP methods (GET, POST, PUT, DELETE, etc.) are allowed from the requesting origin.
  • Access-Control-Allow-Headers: Specifies which HTTP headers are allowed in the actual request (e.g., Content-Type, Authorization).
  • Access-Control-Allow-Credentials: Indicates whether the browser should include credentials (cookies, HTTP authentication) with the request.

Example of a CORS response:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type

3. Actual Request:

If the preflight request is successful and the server allows the origin, the browser will send the actual request (e.g., GET, POST, etc.). The server’s response will again include CORS headers, which the browser checks before allowing access to the data.

Example of an actual request:

GET /api/data HTTP/1.1
Host: api.example.com
Origin: https://example.com
Content-Type: application/json

The server might respond with:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://example.com
Content-Type: application/json

If CORS is not properly configured, the browser will block the response, and the JavaScript running on the page won’t have access to the data.


4. CORS Headers and Their Functions

  • Access-Control-Allow-Origin: Specifies which origin(s) are allowed to access the resource. It can be set to a specific domain (e.g., https://example.com) or a wildcard (*) to allow all origins.

  • Access-Control-Allow-Methods: Defines which HTTP methods are permitted for cross-origin requests. Common methods include GET, POST, PUT, DELETE.

  • Access-Control-Allow-Headers: Specifies which headers can be included in the actual request. For example, Content-Type, Authorization.

  • Access-Control-Allow-Credentials: Indicates whether credentials (like cookies or HTTP authentication) can be included in cross-origin requests. If true, the browser will send credentials along with the request.

  • Access-Control-Expose-Headers: Allows the server to specify which response headers can be exposed to the client-side application.

  • Access-Control-Max-Age: Specifies how long the results of the preflight request can be cached by the browser in seconds.


5. Common CORS Issues and Solutions

  • Issue 1: CORS not configured on the server: If CORS is not properly configured on the API server, browsers will block requests. This can be solved by setting appropriate CORS headers in the server response.

  • Issue 2: Missing Access-Control-Allow-Origin header: If the server does not include the Access-Control-Allow-Origin header in the response, the browser will not allow the client to access the response. To fix this, ensure that the server includes the correct origin header.

  • Issue 3: Preflight request fails: If the preflight request returns an error (e.g., the server does not allow certain methods or headers), the actual request will be blocked. Ensure that the server allows the required methods and headers.


6. Conclusion

CORS is an essential part of web security that governs how resources can be shared across different domains. It prevents malicious websites from accessing sensitive data from another origin and ensures that only trusted websites can interact with an API. Properly configuring CORS on the server is crucial for enabling legitimate cross-origin requests, especially in modern web applications and APIs where the client (front-end) and server (back-end) are often hosted on different domains or subdomains.

Question: What are webhooks and how do they differ from APIs?

Answer:

Webhooks and APIs are both methods used for communication between applications or services over the internet, but they function in fundamentally different ways. Let’s break down what each of these concepts is and how they differ:


1. What are Webhooks?

A webhook is a user-defined HTTP callback or push notification mechanism that enables one system to send real-time data or notifications to another system as soon as an event occurs. Instead of the receiving system continuously polling or requesting data from the sender, the sender automatically triggers an HTTP request to a predefined URL (the webhook URL) when a specified event occurs.

How Webhooks Work:

  • Event-driven: Webhooks are typically set up to notify a server about an event, such as a new user registration, payment received, or an issue being closed in a bug tracker.
  • Push mechanism: Once the event occurs, the webhook sends an HTTP POST request (sometimes including data in JSON or XML format) to the configured URL endpoint of the receiving system.
  • Real-time notifications: Webhooks are ideal for real-time notifications or updates, because they eliminate the need for the receiving system to continually check for changes or updates.

Example of Webhook:

Imagine you are using an e-commerce platform (like Shopify), and you want to be notified whenever a new order is placed. You would configure a webhook with Shopify to send a POST request to your server whenever a new order is placed. Your server then processes the request and handles the new order.

{
  "order_id": 12345,
  "total_price": 59.99,
  "items": [
    {"name": "Laptop", "quantity": 1}
  ]
}

2. What are APIs?

An API (Application Programming Interface) is a set of rules and protocols that allows one system to interact with another. An API exposes a set of functions or endpoints that can be called by other applications to request data, perform actions, or retrieve resources.

How APIs Work:

  • Request-response model: In contrast to webhooks, APIs are typically based on a request-response model. The client (or consumer) makes a request to the server (or provider), and the server responds with data or an action result.
  • Poll-based mechanism: With an API, the client application must actively make requests to retrieve data or perform actions. This is typically done using HTTP methods (GET, POST, PUT, DELETE, etc.).

Example of API:

Consider a weather service that provides an API. To get the current weather for a specific location, a client application makes an HTTP GET request to the weather API, specifying the location.

Example:

GET /api/weather?location=London

The API responds with weather data in JSON or XML format:

{
  "location": "London",
  "temperature": "18°C",
  "condition": "Partly Cloudy"
}

3. Key Differences Between Webhooks and APIs:

FeatureWebhooksAPIs
Communication TypePush-based: Server pushes data to the client when an event occurs.Pull-based: Client actively requests data from the server.
Request TypeTypically an HTTP POST request from the server to the client.Typically HTTP GET, POST, PUT, DELETE requests from client to server.
Triggered byEvents (e.g., new order, payment received).Client requests (e.g., retrieving data, performing actions).
Real-timeYes, webhooks provide real-time data.No, API calls may not be in real-time unless frequently polled.
EfficiencyMore efficient for event-driven updates, as no polling is needed.Can be inefficient for frequent polling (e.g., asking every minute if there’s new data).
Use CaseNotification system, event handling, or real-time updates.Data retrieval, CRUD operations, interacting with services.
ReliabilityDependent on the receiver being available to handle the webhook notification.Dependent on the client initiating requests and the server responding to them.
Setup ComplexityRelatively simple: you define the URL to which the data is sent.More complex: you may need to define authentication, rate limits, and other configurations.

4. When to Use Webhooks vs. APIs?

  • Use Webhooks:

    • When you need real-time data updates from another service.
    • When the event you are interested in happens infrequently (e.g., new user registration, new payment, etc.), and you don’t want to poll continuously.
    • For notifications about state changes in the system, such as updates to a database, user activity, or status changes.
  • Use APIs:

    • When you need to actively retrieve data, either on-demand or in periodic intervals.
    • When the communication is based on client-initiated actions, like submitting forms, retrieving information, or interacting with a system.
    • When you need to perform complex actions or retrieve specific sets of data from a service.

5. Summary:

  • Webhooks are event-driven, push-based mechanisms that send data automatically when an event occurs. They are efficient for real-time updates or notifications and are typically used when you need to be informed of an event or state change as soon as it happens.

  • APIs, on the other hand, require the client to actively make requests to retrieve data or perform actions. They are pull-based and ideal for systems where you need to request data on demand or interact with the service in a more structured way.

In essence, webhooks are used for passive notifications and APIs are used for active requests and data retrieval.

Question: What are some best practices for designing a RESTful API?

Answer:

Designing a RESTful API involves creating an efficient and user-friendly way for applications to communicate over HTTP. Following best practices ensures that your API is easy to use, maintain, and scale while adhering to standards. Here are some key best practices for designing a RESTful API:


1. Use HTTP Methods Correctly

  • GET: Retrieve data without modifying it. It should be idempotent (multiple requests should yield the same result).
  • POST: Create new resources. It is used when submitting data to the server (e.g., creating a new record).
  • PUT: Update an existing resource or create a resource if it does not exist. It is idempotent.
  • PATCH: Partially update an existing resource (e.g., updating one field of a resource).
  • DELETE: Remove a resource.

By adhering to these HTTP methods, you ensure that your API remains consistent with the REST principles.


2. Use Meaningful and Consistent Resource URIs

  • Naming Conventions: Use plural nouns for resource names to represent collections (e.g., /users, /products).
  • Hierarchical Structure: Organize the API with a hierarchical structure for related resources (e.g., /users/{userId}/orders).
  • Avoid Verbs in URIs: URIs should refer to nouns (resources), not verbs. For example, /getUser should be avoided in favor of /users.

Examples:

  • Good: /users, /users/{id}/orders
  • Bad: /getUsers, /addUser

3. Provide a Clear and Predictable API Response Format

  • Consistency: Maintain consistency in the structure of the responses, such as using the same naming conventions for keys and objects.
  • JSON Format: The most common format for RESTful APIs is JSON. Use it by default, but XML can be an alternative if necessary.

Example JSON Response:

{
  "id": 1,
  "name": "John Doe",
  "email": "[email protected]",
  "orders": [
    {
      "order_id": 123,
      "total": 50.00
    }
  ]
}

4. Handle Errors Properly

  • Use HTTP Status Codes: Leverage standard HTTP status codes to convey the result of the API request:

    • 200 OK: The request was successful.
    • 201 Created: The resource was successfully created.
    • 400 Bad Request: The request was malformed or invalid.
    • 401 Unauthorized: Authentication is required and has failed or has not been provided.
    • 403 Forbidden: The user does not have permission to access the resource.
    • 404 Not Found: The requested resource could not be found.
    • 500 Internal Server Error: The server encountered an unexpected condition.
  • Provide Meaningful Error Messages: Return detailed error messages to help the client understand what went wrong, including any missing or invalid parameters.

Example Error Response:

{
  "error": {
    "code": 400,
    "message": "The 'email' field is required."
  }
}

5. Enable Pagination for Large Collections

When dealing with large sets of data (e.g., retrieving all users or all products), implement pagination to prevent overwhelming the client and the server. Use parameters like limit, offset, or page for pagination.

Example:

GET /users?limit=10&page=2

This returns 10 users, starting from the 11th user (page 2).


6. Use Query Parameters for Filtering, Sorting, and Searching

Allow clients to filter, sort, and search the data using query parameters. This allows clients to retrieve specific data without needing to make multiple requests.

  • Filtering: Use query parameters to allow filtering by specific fields.

    GET /products?category=electronics&price_min=100&price_max=500
  • Sorting: Allow sorting by different fields.

    GET /products?sort=price_desc
  • Searching: Provide a search query parameter for full-text search.

    GET /products?search=laptop

7. Version Your API

Versioning your API is important to ensure backward compatibility as the API evolves. There are different strategies for versioning:

  • URI Versioning: Include the version number in the URI (e.g., /v1/users).
  • Query Parameter Versioning: Include the version number as a query parameter (e.g., /users?version=1).
  • Header Versioning: Specify the version in the request header (e.g., X-API-Version: 1).

Example (URI Versioning):

GET /v1/products

8. Support Caching

To improve performance and reduce load on the server, use HTTP caching headers. This allows clients to cache responses and avoid redundant requests.

  • Cache-Control: Directs how and for how long the content should be cached.
  • ETag: A unique identifier for a specific version of the resource. If the resource hasn’t changed, the server responds with a 304 Not Modified status.

Example (Caching Header):

Cache-Control: max-age=3600
ETag: "abc123"

9. Implement Authentication and Authorization

  • Use Token-based Authentication: Implement authentication mechanisms such as OAuth 2.0, JWT (JSON Web Tokens), or API keys to ensure secure access to the API.
  • Enforce Role-based Authorization: Use role-based access control (RBAC) to restrict access to certain resources or actions based on the user’s role.

10. Document the API

Clear and detailed documentation is essential for any API. This allows developers to easily understand how to use the API and its available endpoints. Tools like Swagger/OpenAPI can help automatically generate API documentation.

Include the following in your API documentation:

  • Endpoint descriptions (including parameters, request methods, and responses).
  • Authentication information.
  • Error codes and their meanings.
  • Examples of requests and responses.

11. Secure Your API

Ensure the security of your API by following best practices such as:

  • Use HTTPS: Ensure that all communication between clients and the API is encrypted using HTTPS.
  • Input Validation: Sanitize user input to prevent injection attacks (e.g., SQL injection, XSS).
  • Limit Request Rate: Implement rate limiting to prevent abuse and ensure fair usage.
  • Cross-Origin Resource Sharing (CORS): Configure CORS to control which domains can access your API.

12. Make the API Stateless

Ensure that each API request contains all the information necessary for the server to process it. This means that the server should not store any session information between requests. The API should be stateless, meaning that each request is independent and self-contained.


Conclusion

By adhering to these best practices, you ensure that your RESTful API is well-designed, user-friendly, and scalable. It will also be easier for developers to integrate with and maintain over time. Key principles like using standard HTTP methods, providing meaningful responses, and securing the API are essential for creating an effective and reliable API.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as api interview questions, api interview experiences, and details about various api job positions. Click here to check it out.

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now