🎓 BookMCQ
← Back to 25. Introduction to Application Layer

📝 Application Programming Interface (API) in networking (23 MCQs)

Programming Interfaces Between Applications and Network Services

A networking API exposes operations that application programs use to access communication services. It hides many operating-system and protocol-stack details behind functions, classes, and data structures. Socket APIs provide common operations for creating endpoints, assigning addresses, connecting peers, and transferring data, allowing application code to use TCP or UDP. It provides a stable programming boundary between application logic and network facilities.

Socket API Operations and Address Structures

A typical socket interface includes creation, binding, connection, listening, acceptance, sending, receiving, and closure operations. Address structures represent protocol family, IP address, and port. The API may report errors through return values, exceptions, or error codes, so programs must check results rather than assuming every operation succeeds. The exact function names vary between platforms and programming languages.

Mapping Program Calls to Network Activity

When a program calls send or write on a connected TCP socket, the API passes application bytes to the local networking stack. TCP segments the byte stream and manages sequence numbers, acknowledgments, and retransmission as needed. A receive call returns available stream bytes; it does not necessarily return one complete application message.

Choosing an API for a Datagram Client

A C program can create an IPv4 UDP socket with socket(AF_INET, SOCK_DGRAM, 0), fill a sockaddr_in destination, and call sendto. The server receives the datagram with recvfrom and learns the sender address. These calls expose message-oriented datagram communication without requiring TCP's listen and accept sequence. The API exposes destination selection and sender identification to the application.

APIs, Protocols and Application Portability

An API is a programming interface, not the wire protocol itself. Different operating systems may expose similar socket operations, while HTTP, DNS, TCP, and UDP specify communication behavior across hosts. Higher-level APIs can wrap sockets to provide HTTP requests or name resolution, improving portability and reducing low-level coding. The interface can change while interoperable protocol rules remain the same.

Misconceptions About Networking APIs

'The socket API is a transport protocol' confuses function calls with TCP or UDP rules. 'One send call always equals one TCP segment' ignores buffering and TCP segmentation. 'An API guarantees remote application success' is also incorrect because it reports local operation results, not whether the peer completed the requested task.

Recognizing API Calls and Their Effects

For examinations, distinguish socket types such as stream and datagram, identify the purpose of bind, listen, accept, and connect, and match sendto or recvfrom with datagram exchange. Explain what address structures contain and why return values matter. Separate an API operation from the protocol action that may follow inside the network stack.

Networking API Terminology

  • API - Defined interface for using software services.
  • Socket - Communication endpoint exposed by a networking API.
  • SOCK_STREAM - Socket type commonly used with TCP.
  • SOCK_DGRAM - Socket type commonly used with UDP.
  • sockaddr - Structure representing a protocol endpoint address.
  • System call - Request for an operating-system service.
7
Easy
10
Medium
6
Hard

📝 All Application Programming Interface (API) in networking MCQs

Q1. When an API response includes the HTTP status code 401, which of the following is the most likely cause?

A.The request was successfully processed
B.The client failed to provide valid authentication credentials ✅
C.The requested resource could not be found
D.The server encountered an internal error
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: A 401 status indicates that the server recognized the request but refuses to fulfill it because the client did not supply valid authentication information. This is distinct from success (200), not‑found (404), or server errors (5xx). Therefore the correct inference is that authentication credentials are missing or invalid.

Q2. A client calls an endpoint without supplying a required query parameter and receives an error. What is the most probable HTTP status returned?

A.Server overload
B.Invalid request syntax
C.Authentication failure
D.Missing required parameter ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: When a mandatory parameter is omitted, the server cannot process the request as specified, so it typically returns a 400 Bad Request indicating client‑side input error. Overload (503), authentication issues (401), or syntax errors unrelated to missing data are less appropriate, making the missing‑parameter response the most likely.

Q3. If a developer continues to use an endpoint that has been officially deprecated, what outcome is most likely for client applications?

A.Improved performance
B.Backward compatibility is guaranteed
C.Clients may experience runtime errors ✅
D.No impact on functionality
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: Deprecated endpoints are no longer maintained and may be removed or altered in future releases. Clients that still depend on them risk encountering unexpected response formats, missing fields, or outright failures, leading to runtime errors. Compatibility is not assured, and performance gains are unlikely.

Q4. Which statement best distinguishes REST from SOAP?

A.REST uses XML exclusively
B.SOAP is stateless
C.REST relies on standard HTTP verbs while SOAP defines its own envelope ✅
D.SOAP supports caching
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: REST embraces the uniform interface of HTTP, using verbs like GET, POST, PUT, and DELETE, whereas SOAP wraps messages in a custom XML envelope and operates over a variety of protocols. This fundamental difference in how operations are expressed and transmitted makes option C the accurate distinction.

Q5. When comparing simple API keys to OAuth 2.0, which advantage does OAuth provide?

A.API keys provide token expiration
B.OAuth tokens are always longer than API keys
C.OAuth includes delegated access and scopes ✅
D.API keys are encrypted by default
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: OAuth 2.0 introduces the concept of scopes and delegated permissions, allowing a client to request only the access it needs and to revoke it independently of the resource owner. Simple API keys lack this granularity and cannot express fine‑grained delegation, making OAuth’s scoped delegation the key advantage.

Q6. How do asynchronous API calls affect system throughput compared to synchronous calls?

A.Synchronous calls increase throughput
B.Asynchronous calls allow overlapping I/O ✅
C.Both have identical throughput
D.Asynchronous calls block the client thread
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Asynchronous requests let the client continue processing while the server handles I/O, permitting multiple operations to be in flight simultaneously. This overlap reduces idle waiting time and raises overall throughput, whereas synchronous calls force the client to wait for each response before proceeding, limiting parallelism.

Q7. Which characteristic most accurately describes a private API?

A.Public APIs are always free
B.Private APIs require authentication ✅
C.Public APIs cannot be versioned
D.Private APIs are undocumented
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Private APIs are intended for internal use or restricted partners, so they typically enforce authentication mechanisms such as tokens or certificates to control access. This distinguishes them from public APIs, which are openly available, and aligns with the definition of a private API requiring authentication.

Q8. What does it mean for an API operation to be idempotent?

A.The operation can be repeated without changing the result ✅
B.The operation always modifies state
C.The operation depends on the client session
D.The operation is asynchronous only
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: Idempotence means that performing the same request multiple times yields the same effect as a single execution; no additional side effects occur after the first call. This property is essential for safe retries and aligns with the definition given in option A.

Q9. How does proper API versioning support backward compatibility?

A.Versioning eliminates the need for compatibility
B.Proper versioning ensures older clients continue to work ✅
C.Version numbers are irrelevant
D.Backward compatibility is impossible with versioning
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: When an API introduces a new version, existing clients can continue using the previous version identifier, preserving their expected behavior. This strategy allows developers to add features or changes without breaking legacy integrations, fulfilling the promise of backward compatibility through controlled versioning.

Q10. Which design pattern best enables pagination, filtering, and caching in a RESTful API?

A.Use a fixed page size for all responses
B.Include query parameters for limit, offset, and filter criteria, and send appropriate Cache‑Control headers ✅
C.Return the entire dataset in one response
D.Omit cache headers to force fresh data each request
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: By exposing limit, offset, and filter parameters, the API lets clients request only the needed slice of data, reducing payload size. Adding Cache‑Control directives informs intermediaries about freshness, allowing repeated queries to be served from cache when appropriate. This combination satisfies pagination, filtering, and caching requirements.

Q11. In a truly RESTful service, how is statelessness achieved?

A.The server must store client context between requests
B.Each request contains all information needed to process it ✅
C.Statelessness requires the use of session cookies
D.None of the above
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Statelessness mandates that the server does not retain any client‑specific state between requests; therefore, every HTTP request must carry all data (e.g., authentication tokens, query parameters) required for the server to understand and act upon it. This eliminates server‑side session storage and aligns with REST principles.

Q12. How does GraphQL address the problems of over‑fetching and under‑fetching common in REST?

A.GraphQL forces fixed responses
B.Clients specify exactly which fields they need ✅
C.GraphQL uses traditional REST endpoints
D.Over‑fetching is increased in GraphQL
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: GraphQL lets the client declare the precise fields required in the query, so the server returns only that subset of data. This eliminates the need to retrieve whole resources (over‑fetching) or make multiple calls to gather missing pieces (under‑fetching), directly solving the inefficiencies of conventional REST responses.

Q13. What role does an API gateway play in microservices communication?

A.It eliminates the need for service discovery
B.It can perform request routing, authentication, and response aggregation ✅
C.The gateway stores persistent data for services
D.Gateways replace microservices entirely
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: An API gateway sits at the edge of a microservice architecture, handling cross‑cutting concerns such as routing inbound requests to the appropriate service, enforcing authentication and authorization policies, and optionally aggregating responses from multiple services into a single payload for the client.

Q14. Which of the following best defines an Application Programming Interface?

A.A hardware component
B.A set of routines allowing software components to interact ✅
C.An operating system
D.A database schema
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: An API is a collection of defined methods, protocols, and tools that enable different software applications or components to communicate and exchange data, abstracting underlying implementation details. This definition matches option B, distinguishing it from hardware, OS, or database concepts.

Q15. What does the acronym CRUD stand for in the context of data‑manipulating APIs?

A.Create, Read, Update, Delete ✅
B.Compute, Render, Upload, Download
C.Connect, Retrieve, Unify, Deploy
D.None of the above
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: CRUD is the standard set of four basic operations used to manage persistent storage: Create inserts new records, Read retrieves existing data, Update modifies records, and Delete removes them. This widely‑used terminology aligns with option A.

Q16. If a request omits a required query parameter, which HTTP status code is the most appropriate response?

A.200 OK
B.401 Unauthorized
C.400 Bad Request ✅
D.500 Internal Server Error
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: A missing mandatory parameter makes the request malformed from the server's perspective, so the correct response is 400 Bad Request, indicating that the client must correct the input. Success (200), authentication issues (401), or server failures (500) are unrelated to this specific client error.

Q17. What is a common consequence of serving stale data from an improperly configured cache?

A.Improves data freshness
B.Causes clients to see outdated information ✅
C.Has no effect on client behavior
D.Guarantees data consistency across requests
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: When a cache returns data that is no longer current, clients may act on obsolete information, leading to inconsistencies, incorrect decisions, or synchronization problems. The primary risk is presenting outdated content, which undermines trust and can cause functional errors.

Q18. When an API returns a 429 status, what can be inferred about the client's behavior?

A.The server is down
B.The client exceeded the allowed request rate ✅
C.The requested resource was not found
D.Authentication failed
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: A 429 Too Many Requests response signals that the client has sent more requests than the server's rate‑limit policy permits within a given time window. This inference guides the client to back‑off or retry later, rather than indicating server downtime or authentication issues.

Q19. If an API contract specifies that a response field must be an integer, but the server sends a string, what is the most likely impact on client applications?

A.It guarantees backward compatibility
B.It causes runtime errors due to unexpected payload types ✅
C.It improves overall performance
D.It has no impact on client behavior
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Violating the contract by delivering a different data type breaks the client's expectations, often leading to parsing failures, exceptions, or incorrect calculations. Such mismatches directly cause runtime errors, whereas compatibility and performance remain unaffected or may degrade.

Q20. What is a key trade‑off when choosing URL path versioning versus custom header versioning for an API?

A.URL versioning is invisible to clients
B.Header versioning requires clients to modify request headers ✅
C.Both approaches behave identically for caching
D.Header versioning cannot be used with REST
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Using a custom header to convey the API version forces client developers to add or modify header fields in each request, which can increase implementation complexity. In contrast, embedding the version in the URL is straightforward for most HTTP clients, making the header approach the more burdensome option.

Q21. How does an API gateway differ from a service mesh in handling traffic?

A.Gateways manage external inbound traffic while a service mesh focuses on internal service‑to‑service communication ✅
B.A service mesh replaces the need for an API gateway
C.Both are identical in function
D.Gateways only provide load balancing
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: An API gateway acts as the entry point for client requests, enforcing security, routing, and transformation at the network edge. A service mesh, however, operates within the cluster to manage east‑west traffic, providing observability, retries, and mutual TLS between services. This distinction matches option A.

Q22. Which statement correctly contrasts a monolithic API with an API composition approach?

A.A monolithic API aggregates all functionality in one endpoint, while composition splits logic across multiple services
B.Monolithic APIs cannot be versioned ✅
C.Composition always reduces latency
D.Both are equivalent in design
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: In a monolithic design, a single service exposes a large, often unwieldy API surface. API composition, by contrast, orchestrates multiple specialized services, each offering focused endpoints, and aggregates their responses for the client. This modular approach improves maintainability and scalability, aligning with option B.

Q23. When designing an API that must handle authentication, rate limiting, and logging, which architectural pattern best supports these concerns?

A.Implement all features in a single endpoint function
B.Chain middleware components, each addressing one concern ✅
C.Omit logging to improve performance
D.Use only client‑side checks for security
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Middleware allows developers to separate cross‑cutting concerns into distinct, reusable layers that execute sequentially for each request. Authentication, rate limiting, and logging can each be encapsulated in its own middleware, promoting clean code, easier testing, and consistent enforcement across the entire API surface.

🔗 Related Topics (MCQs)