Most Frequently asked Interview Questions of api
Question: What is an endpoint in an API?
Answer:
An endpoint in an API is a specific URL (Uniform Resource Locator) that corresponds to a particular resource or a set of actions that can be performed using an HTTP request. It is the point of entry through which an API interacts with other systems, enabling them to communicate and exchange data.
Endpoints are essentially the URLs you interact with when making requests to an API. Each endpoint typically represents a resource (such as a user, product, or order) or a specific operation that can be performed on that resource.
Key Components of an API Endpoint:
-
Base URL:
- The base URL is the root address of the API, which often stays constant.
- Example:
https://api.example.com/
-
Path:
- The path identifies the specific resource or action you want to access or perform.
- Example:
/users
,/products
,/orders
-
Query Parameters (optional):
- Query parameters provide additional filters or instructions for the request, typically after the
?
symbol in the URL. - Example:
?id=123&status=active
- Query parameters provide additional filters or instructions for the request, typically after the
-
HTTP Method:
- The HTTP method (such as GET, POST, PUT, DELETE) defines the action to be performed on the resource identified by the endpoint.
- Example: GET, POST, PUT, DELETE
Example of an API Endpoint:
Suppose we have an API for managing users, and the base URL is https://api.example.com/
.
-
GET Endpoint (Retrieve user data):
- URL:
https://api.example.com/users/{id}
- HTTP Method:
GET
- Action: Retrieve the details of a user with the specified ID.
- Example:
GET https://api.example.com/users/123
would retrieve the details of the user with ID123
.
- URL:
-
POST Endpoint (Create new user):
- URL:
https://api.example.com/users
- HTTP Method:
POST
- Action: Create a new user by sending the user’s data (in the body of the request).
- Example:
POST https://api.example.com/users
would create a new user.
- URL:
-
DELETE Endpoint (Delete a user):
- URL:
https://api.example.com/users/{id}
- HTTP Method:
DELETE
- Action: Delete the user with the specified ID.
- Example:
DELETE https://api.example.com/users/123
would delete the user with ID123
.
- URL:
-
PUT Endpoint (Update user data):
- URL:
https://api.example.com/users/{id}
- HTTP Method:
PUT
- Action: Update the user details with the specified ID.
- Example:
PUT https://api.example.com/users/123
would update the user with ID123
.
- URL:
How Endpoints Relate to RESTful APIs:
In RESTful APIs, each endpoint typically represents a resource (such as users
, products
, etc.) or a specific operation (like creating or updating a user). The combination of HTTP methods (GET, POST, PUT, DELETE) and the endpoint path defines the action that will be taken on the resource.
For example:
GET /users
→ Retrieve a list of users.POST /users
→ Create a new user.GET /users/{id}
→ Retrieve a specific user by ID.PUT /users/{id}
→ Update an existing user by ID.DELETE /users/{id}
→ Delete a user by ID.
Endpoints and Query Parameters:
Endpoints can also include query parameters, which are used to filter or modify the data returned from the API. These parameters are added after the endpoint path and are separated by ?
or &
symbols.
Example:
GET https://api.example.com/users?age=30&status=active
- This request would retrieve all users who are 30 years old and have a status of “active”.
Summary:
An API endpoint is a specific URL (or URI) that allows interaction with a resource or service provided by the API. It represents the entry point where requests are made to retrieve or modify data. The HTTP method used with the endpoint determines the operation to perform (e.g., GET for reading, POST for creating, PUT for updating, DELETE for deleting).
Question: What is the role of status codes in API responses?
Answer:
Status codes in API responses are part of the HTTP response sent from the server to the client after a request is made. They provide important information about the outcome of the API request and help the client understand whether the request was successful, if there was an error, or if further action is required.
Status codes are standardized, with each code representing a specific category or type of result. They are categorized into five classes, based on the first digit of the code:
-
1xx (Informational)
- Purpose: Indicates that the request was received and is being processed, but no final response is yet available.
- Examples:
100 Continue
101 Switching Protocols
-
2xx (Successful)
- Purpose: Indicates that the request was successfully received, understood, and processed.
- Examples:
200 OK
: The request was successful, and the response body contains the requested data (if any).201 Created
: The request was successful, and a new resource was created.204 No Content
: The request was successful, but there is no content to return (typically used for DELETE requests).
-
3xx (Redirection)
- Purpose: Indicates that further action is needed to fulfill the request, usually involving a redirection to another resource.
- Examples:
301 Moved Permanently
: The resource has been permanently moved to a new URL.302 Found
: The resource has been temporarily moved to another URL.304 Not Modified
: The resource has not been modified since the last request (typically used for caching purposes).
-
4xx (Client Error)
- Purpose: Indicates that the client seems to have made an error in the request, either due to invalid syntax or a lack of necessary information.
- Examples:
400 Bad Request
: The server could not understand the request due to invalid syntax.401 Unauthorized
: The request requires user authentication.403 Forbidden
: The server understands the request but refuses to authorize it.404 Not Found
: The requested resource could not be found on the server.422 Unprocessable Entity
: The server understands the content type of the request but was unable to process the contained instructions (often used in validation errors).
-
5xx (Server Error)
- Purpose: Indicates that the server has encountered an error or is otherwise incapable of performing the request.
- Examples:
500 Internal Server Error
: The server encountered an unexpected condition that prevented it from fulfilling the request.502 Bad Gateway
: The server received an invalid response from an upstream server while processing the request.503 Service Unavailable
: The server is temporarily unavailable, often due to maintenance or overload.504 Gateway Timeout
: The server did not receive a timely response from an upstream server or database.
Role of Status Codes in API Responses:
-
Indicate Success or Failure:
- Status codes inform the client whether the API request was successful or failed. For instance, a
200 OK
indicates a successful operation, while a400 Bad Request
signals an issue with the request sent by the client.
- Status codes inform the client whether the API request was successful or failed. For instance, a
-
Provide Context on the Error:
- For failed requests, the status code helps the client understand the nature of the error. For example, a
401 Unauthorized
suggests a problem with authentication, whereas404 Not Found
indicates that the requested resource is unavailable.
- For failed requests, the status code helps the client understand the nature of the error. For example, a
-
Enable Handling of Responses Programmatically:
- APIs often use status codes to allow clients to handle responses programmatically. For instance, if an API returns a
200 OK
, the client can proceed to process the data. However, if it returns a500 Internal Server Error
, the client may decide to retry the request or show an error message.
- APIs often use status codes to allow clients to handle responses programmatically. For instance, if an API returns a
-
Support Debugging and Logging:
- Status codes help both developers and system administrators diagnose and debug issues. By looking at the status code returned in a failed API call, it’s easier to pinpoint where things went wrong, whether it’s an issue with the server, authentication, or resource availability.
-
Improve User Experience:
- Providing meaningful status codes along with descriptive error messages enhances the user experience. For example, a
404 Not Found
status accompanied by a helpful message like “The requested user does not exist” is far more informative than just a generic error message.
- Providing meaningful status codes along with descriptive error messages enhances the user experience. For example, a
-
Enable Redirection:
- Status codes in the 3xx range help with directing the client to another URL. For instance, a
301 Moved Permanently
status code informs the client that the resource has been moved, prompting the client to make a request to the new URL.
- Status codes in the 3xx range help with directing the client to another URL. For instance, a
Commonly Used Status Codes in API Responses:
2xx (Success):
- 200 OK: The request was successful, and the response contains the requested data.
- 201 Created: A new resource has been successfully created.
- 204 No Content: The request was successful, but there is no data to return (common in DELETE requests).
4xx (Client Error):
- 400 Bad Request: The request was malformed or missing required parameters.
- 401 Unauthorized: The request requires authentication or the provided credentials are invalid.
- 403 Forbidden: The server understands the request, but the client does not have permission to access the resource.
- 404 Not Found: The requested resource could not be found.
- 422 Unprocessable Entity: The request is well-formed but contains semantic errors (often used in form validation errors).
5xx (Server Error):
- 500 Internal Server Error: A generic error when the server encounters an unexpected condition.
- 502 Bad Gateway: The server is acting as a gateway or proxy and received an invalid response from an upstream server.
- 503 Service Unavailable: The server is temporarily unavailable (e.g., during maintenance).
Example of Status Codes in Action:
-
GET /users (Retrieve a list of users):
- Response:
200 OK
— The list of users is returned successfully.
- Response:
-
POST /users (Create a new user):
- Response:
201 Created
— The user was successfully created.
- Response:
-
GET /users/123 (Retrieve a specific user):
- Response:
404 Not Found
— The user with ID123
does not exist.
- Response:
-
DELETE /users/123 (Delete a user):
- Response:
204 No Content
— The user was deleted successfully, but no content is returned.
- Response:
-
POST /login (User login attempt):
- Response:
401 Unauthorized
— The user’s credentials are invalid.
- Response:
Conclusion:
Status codes are crucial in API responses as they provide essential information about the success, failure, or state of the API request. By using status codes effectively, developers can improve the clarity and functionality of the API, making it easier for clients to handle responses and troubleshoot errors.
Question: What are the key differences between GET, POST, PUT, and DELETE methods in an API?
Answer:
The GET, POST, PUT, and DELETE methods are the four most common HTTP methods used to interact with resources in RESTful APIs. They correspond to the basic CRUD (Create, Read, Update, Delete) operations. Each method serves a distinct purpose when interacting with resources on a server.
Here’s a breakdown of their key differences:
1. GET Method:
- Purpose: Retrieve data from the server (Read).
- Description: The
GET
method is used to fetch or retrieve data from a resource without modifying it. It should be safe and idempotent, meaning repeated requests will have the same effect (i.e., no changes on the server). - Usage: When you want to get information, such as fetching a list of users or getting the details of a specific user.
- Request Body: Typically does not contain a body (data is passed via URL parameters or query strings).
- Example:
GET /users
→ Retrieve a list of all users.GET /users/123
→ Retrieve data for the user with ID123
.
- Idempotent: Yes (multiple identical GET requests will not change the state of the resource).
2. POST Method:
- Purpose: Send data to the server to create a new resource (Create).
- Description: The
POST
method is used to submit data to the server, often resulting in the creation of a new resource. It is not idempotent, meaning sending the same request multiple times could result in different outcomes (such as creating multiple resources). - Usage: When you need to create a new record, like adding a new user or submitting a form.
- Request Body: Contains the data to be sent to the server (e.g., the data for a new user).
- Example:
POST /users
→ Create a new user by sending the user’s data in the request body.
- Idempotent: No (sending the same request multiple times may create multiple resources).
3. PUT Method:
- Purpose: Update an existing resource or create a new resource if it does not exist (Update).
- Description: The
PUT
method is used to update an existing resource or replace the entire resource with the new data sent in the request body. If the resource does not exist, it may create a new resource at the specified location. - Usage: When you need to update an existing record or replace an entire resource.
- Request Body: Contains the full updated data of the resource.
- Example:
PUT /users/123
→ Update the user with ID123
using the data provided in the request body.
- Idempotent: Yes (repeated PUT requests with the same data will not create duplicates or change the resource beyond the first request).
4. DELETE Method:
- Purpose: Delete a resource from the server (Delete).
- Description: The
DELETE
method is used to remove a resource from the server. It can be used to delete specific resources or collections of resources. LikeGET
, it should be idempotent, meaning multiple DELETE requests for the same resource should have the same effect (i.e., the resource is deleted once and cannot be deleted again). - Usage: When you need to delete a specific record or resource, such as removing a user or item.
- Request Body: Typically does not contain a body (resource identification is done via the URL).
- Example:
DELETE /users/123
→ Delete the user with ID123
.
- Idempotent: Yes (deleting the same resource multiple times will have no additional effect after the first deletion).
Summary of Differences:
HTTP Method | Purpose | Action (CRUD) | Request Body | Idempotent | Example |
---|---|---|---|---|---|
GET | Retrieve data from the server | Read | No | Yes | GET /users/123 (Retrieve user) |
POST | Send data to create a resource | Create | Yes | No | POST /users (Create new user) |
PUT | Update or create a resource | Update (Replace) | Yes | Yes | PUT /users/123 (Update user) |
DELETE | Delete a resource | Delete | No | Yes | DELETE /users/123 (Delete user) |
Additional Considerations:
- GET and DELETE are considered safe methods because they don’t alter the server’s state (except for removing a resource in the case of DELETE).
- POST and PUT are not safe, as they modify the state of the server (creating or updating resources).
- PUT is often used to update a complete resource, whereas PATCH (another HTTP method) is used for partial updates (modifying only specific fields of a resource).
Real-World Use Cases:
- GET: Retrieve the list of all products available in an e-commerce store.
GET /products
- POST: Add a new product to the store’s inventory.
POST /products
- PUT: Update the details of a specific product (e.g., changing the price or description).
PUT /products/123
- DELETE: Remove a specific product from the store.
DELETE /products/123
Conclusion:
The GET, POST, PUT, and DELETE methods define the core operations that can be performed on resources in a RESTful API, representing the basic CRUD functionality. Understanding their differences and how they are used is crucial for designing and interacting with APIs effectively.
Question: What is API authentication and what are some common methods?
Answer:
API Authentication is the process of verifying the identity of a user or system making a request to an API. Authentication ensures that only authorized users or systems can access the API and perform certain actions (such as reading, writing, or deleting data). It is crucial for securing sensitive data and maintaining the integrity of the system.
There are several methods of API authentication, each serving different security needs and use cases. These methods generally fall under two categories: Basic Authentication and Token-based Authentication.
Common Methods of API Authentication:
-
Basic Authentication:
-
Description: Basic Authentication is one of the simplest methods of API authentication. It involves sending a username and password in the Authorization header of the request. These credentials are usually encoded using Base64 (but not encrypted) before being sent to the API server.
-
Usage: Commonly used for simple applications or APIs that don’t require highly sensitive data.
-
How it works:
- The client sends the username and password in the form:
Authorization: Basic <base64-encoded username:password>
- Example:
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
- The client sends the username and password in the form:
-
Pros:
- Simple and easy to implement.
- Supported by many libraries and frameworks.
-
Cons:
- Not secure if used over an unencrypted connection (i.e., HTTP instead of HTTPS).
- Base64 encoding is not encryption—anyone who intercepts the request can decode the credentials.
- Difficult to scale and manage securely for multiple users.
-
Example:
curl -X GET -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" https://api.example.com/resource
-
-
API Key Authentication:
-
Description: An API key is a unique identifier passed along with the request to authenticate the client. This is a string or token generated by the API provider and is associated with a user or system account.
-
Usage: Used in scenarios where simple authentication is needed, and the API access is limited to specific clients (like for public APIs or third-party integrations).
-
How it works:
- The client includes the API key in the request header, query string, or request body, depending on the API’s design.
- Example (in header):
Authorization: Api-Key <your-api-key>
- Example (in query string):
https://api.example.com/resource?api_key=<your-api-key>
-
Pros:
- Easy to implement and understand.
- Provides a simple method for identifying the user or system making the request.
-
Cons:
- API keys should be kept secure—if exposed, anyone can use them to access the API.
- Cannot track user-specific actions unless combined with other authentication methods.
-
Example:
curl -X GET -H "Authorization: Api-Key 12345abcdef" https://api.example.com/resource
-
-
OAuth 2.0 (Authorization Code Flow):
-
Description: OAuth 2.0 is a widely used delegated authorization protocol. It allows a user to grant a third-party application access to their data without sharing their credentials. OAuth 2.0 involves two main steps: obtaining an access token and using that token to make authorized requests.
-
Usage: Commonly used for scenarios where users need to authorize third-party apps to access their data without sharing credentials (e.g., logging in via Google, Facebook, etc.).
-
How it works:
- The client application redirects the user to an authorization server (e.g., Google, Facebook).
- The user logs in and grants permissions.
- The authorization server returns an authorization code, which the client exchanges for an access token.
- The client sends this access token as part of the request to the API.
-
Pros:
- Highly secure, as credentials are never shared with third parties.
- Supports scopes (limited access to resources) and can be revoked at any time.
- Widely supported by major platforms (Google, Facebook, Microsoft, etc.).
-
Cons:
- More complex to implement compared to simpler methods like API keys.
- Requires the setup of an authorization server and management of tokens.
-
Example:
curl -X GET -H "Authorization: Bearer <access_token>" https://api.example.com/resource
-
-
JWT (JSON Web Token):
-
Description: A JSON Web Token (JWT) is a self-contained token used for securely transmitting information between parties as a JSON object. JWTs can contain claims (user data) and are often used for API authentication after an initial login.
-
Usage: JWT is commonly used for stateless authentication, meaning the server doesn’t need to store session data. It is often used with OAuth 2.0 or standalone authentication systems.
-
How it works:
- After a user logs in, the server generates a JWT and returns it to the client.
- The client sends the JWT with every subsequent API request in the Authorization header.
- The server verifies the JWT and grants access if the token is valid.
-
Pros:
- Stateless authentication (no server-side session management).
- The token is self-contained, meaning it holds user information (e.g., user ID, roles, etc.).
- Can be used across multiple domains and systems.
-
Cons:
- The token can grow large depending on the amount of data it contains.
- Token expiration and revocation management can become complex.
-
Example:
curl -X GET -H "Authorization: Bearer <jwt-token>" https://api.example.com/resource
-
-
HMAC (Hash-based Message Authentication Code):
-
Description: HMAC is a method of verifying both the data integrity and the authenticity of a message. It uses a cryptographic key and a hashing algorithm (e.g., SHA-256) to create a signature that is sent along with the request.
-
Usage: Typically used for secure API communications where the client and server share a secret key. It’s often used in financial APIs or systems where data integrity and security are paramount.
-
How it works:
- The client generates a hash using the secret key and the message data.
- The client sends the message along with the hash (HMAC) in the request.
- The server verifies the hash to ensure the data has not been tampered with and is from a trusted source.
-
Pros:
- Provides strong security by ensuring data integrity and authenticity.
- It’s difficult to forge the HMAC without the shared secret key.
-
Cons:
- The server must securely manage and share the secret key with clients.
- More complex to implement than basic methods.
-
Summary of Common API Authentication Methods:
Authentication Method | Description | Pros | Cons | Example |
---|---|---|---|---|
Basic Authentication | Sends username and password with each request. | Simple, easy to implement. | Not secure over HTTP, lacks scalability. | Authorization: Basic <base64-encoded username:password> |
API Key | Sends a unique API key in each request to authenticate the client. | Simple, easy to implement. | Exposed keys are vulnerable, lacks user tracking. | Authorization: Api-Key <api-key> |
OAuth 2.0 | Delegated authorization allowing third-party apps access to user data without credentials. | Secure, supports scopes, widely adopted. | Complex to implement, requires token management. | Authorization: Bearer <access_token> |
JWT (JSON Web Token) | Self-contained token with user claims used for stateless authentication. | Stateless, scalable, and secure. | Token size can grow, complex revocation management. | Authorization: Bearer <jwt-token> |
HMAC | Uses a cryptographic key to create a signature that verifies the authenticity of a message. | Provides high security and data integrity. | Requires secure key management, complex implementation. | Authorization: HMAC <signature> |
Conclusion:
API authentication is essential for controlling access to resources, ensuring security, and verifying user identity. The choice of authentication method depends on the security requirements, scalability, and complexity of the API. Simple methods like Basic Authentication and API keys are often sufficient for less sensitive APIs, while more secure methods like OAuth 2.0, JWT, and HMAC are necessary for applications that require higher security.
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.