Interview Questions and Answers

What is an API?

  • An application programming interface (API) is a set of rules that specifies how two software programs should interact with each other. It provides a way for one piece of software to request or retrieve data from another piece of software. APIs are a way for different software systems to communicate with each other, allowing them to share data and functionality. They are often used to allow different applications to access the features or data of an operating system, application, or other service. APIs can be used to allow web-based applications to access the functionality of a native application, or to allow different applications or services to communicate with each other.

What is a Web Service?

  • A web service is a method of communication between two electronic devices over a network. It allows one device, such as a server, to send data or functionality to another device, such as a client. Web services are often used to provide a way for different software systems to communicate with each other over the Internet, using standard protocols such as HTTP.
  • There are several types of web services, including:
  • Simple Object Access Protocol (SOAP) web services, which use XML to exchange information.
  • Representational State Transfer (REST) web services, which use HTTP requests to send and receive data.
  • JavaScript Object Notation (JSON) web services, which use a lightweight data interchange format to exchange data.
  • Web services can be accessed using various programming languages, such as Java, Python, or C#. They are often used to allow different applications or devices to communicate with each other, or to provide a way for users to access the functionality of an application or service over the Internet.

Types of Web Services?

  • There are several types of web services that can be used to exchange data or provide access to functionality over a network, including:
  • Simple Object Access Protocol (SOAP) web services: These use the Extensible Markup Language (XML) to structure data and send it over a network. SOAP web services are based on a standard protocol and are often used in enterprise environments.
  • Representational State Transfer (REST) web services: These use HTTP requests to send and receive data and are designed to be lightweight and easy to use. REST web services are often used to expose data and functionality provided by a server or other application.
  • JavaScript Object Notation (JSON) web services: These use a lightweight data interchange format to exchange data between a server and a client. JSON is often used in conjunction with REST web services.
  • Web Application Description Language (WADL) web services: These use an XML-based language to describe the capabilities of a web service. WADL is often used to automatically generate client-side code for consuming a web service.
  • Web Services Description Language (WSDL) web services: These use an XML-based language to describe the functions and properties of a web service. WSDL is often used to automatically generate client-side code for consuming a web service.

Features of Web API?

  • Some features that are commonly found in web APIs include:
  • Standardized communication: Web APIs typically use standard protocols such as HTTP, which allows different software systems to communicate with each other in a consistent way.
  • Accessibility: Web APIs can be accessed over a network, such as the Internet, allowing different applications or devices to communicate with each other regardless of their location.
  • Security: Web APIs can be secured using various methods, such as encryption and authentication, to ensure that only authorized users or applications can access them.
  • Documentation: Web APIs often come with documentation that explains how to use them and what functionality they provide.
  • Versioning: Web APIs may have different versions, which allows developers to update and improve the API without breaking existing applications that use it.
  • Extensibility: Web APIs can be extended or customized to meet the specific needs of an application or service.
  • Interoperability: Web APIs are designed to be used by different software systems and programming languages, which makes them highly interoperable.

why All Web services are APIs, but all APIs are not web services?

  • All web services are APIs, but not all APIs are web services. An API (Application Programming Interface) is a set of rules that specifies how two software programs should interact with each other. An API can be used to allow a software program to communicate with a web service, but it can also be used to allow two software programs to communicate with each other directly.
  • A web service is a type of API that allows communication between software programs over the internet, using the standard protocols of the World Wide Web. Web services use a variety of technologies and standards, such as HTTP, XML, and SOAP, to provide functionality and allow software programs to communicate with each other.
  • So, all web services are APIs, because they are a specific type of API that allows software programs to communicate over the internet. However, not all APIs are web services, because APIs can also be used to allow software programs to communicate with each other directly, without using the internet or the standard protocols of the World Wide Web.

Who can use a Web API?

  • A web API is a set of rules that specifies how two software programs should interact with each other, and can be used to allow communication between software programs over the internet. Anyone who has access to a web API can use it to interact with the software program that provides the API.
  • Generally, web APIs are designed to be used by developers who want to build software applications that interact with other software programs or services over the internet. For example, a developer might use a web API to build a mobile app that retrieves data from a database or web service, or to build a website that interacts with a cloud-based service.
  • However, web APIs are not just limited to developers. Anyone who has access to a web API and the necessary technical skills can use it to interact with the software program or service that provides the API. This could include data analysts, researchers, or anyone else who has a need to access and use data or functionality provided by a software program or service over the internet.

What are some architectural styles for creating a Web API?

  • There are several architectural styles that can be used to create a web API:
  • REST (Representational State Transfer): REST is a popular architectural style for creating web APIs. It uses HTTP methods (such as GET, POST, PUT, and DELETE) to perform operations on resources that are identified using a URI (Uniform Resource Identifier). REST APIs are typically stateless, meaning that each request is independent and does not depend on the state of the server or previous requests.
  • SOAP (Simple Object Access Protocol): SOAP is a protocol for exchanging information in the form of messages over the internet, using XML as the message format. SOAP APIs are often used in enterprise environments to provide a secure, reliable way for different systems to communicate with each other.
  • GraphQL: GraphQL is a query language for APIs that allows clients to request specific data from a server. It was developed by Facebook and is an alternative to REST APIs.
  • gRPC: gRPC is a high-performance, open-source remote procedure call (RPC) framework that uses HTTP/2 and Protocol Buffers (a binary serialization format) to transmit data. gRPC APIs are often used in microservices architectures to allow different services to communicate with each other.
  • There are also other architectural styles that can be used to create web APIs, such as JSON-RPC and XML-RPC. The choice of architectural style for a web API will depend on the needs of the API and the systems that will be using it.

What is API Testing?

  • API testing is a type of software testing that involves testing application programming interfaces (APIs) to ensure that they are working as expected. API tests are typically performed at the integration level, and are designed to validate the functional behavior of the API and ensure that it is reliable, efficient, and secure.
  • API testing can be performed manually or using automated tools. When performing manual API testing, a tester will send requests to the API using a tool such as cURL or Postman, and then evaluate the response that the API sends back. Automated API testing involves using a tool to send requests to the API and then validate the responses that are received.
  • API testing can be used to test the functionality of a web API, as well as the integration of the API with other systems. It can also be used to test the security of an API, by sending requests that are designed to test the API's ability to handle invalid or malicious input.
  • API testing is an important part of the software development process, as it helps to ensure that APIs are working correctly and are able to support the needs of the applications that rely on them.

What are the advantages of API Testing?

There are several advantages to API testing:

  • API testing can be performed early in the development process, as it does not require a GUI to be present. This allows defects to be identified and fixed more quickly, improving the overall quality of the application.
  • API testing is faster and more efficient than GUI testing, as it does not require the testing of individual user interface elements. This makes it possible to test more functionality in less time.
  • API testing is more reliable than GUI testing, as it does not rely on the visual presentation of the application. This means that API tests are less prone to false positives and false negatives.
  • API testing is more cost-effective than GUI testing, as it requires fewer resources and less time to perform.
  • API testing can be used to test the integration of different components of an application, ensuring that they are working together correctly.
  • API testing can be automated, allowing for efficient regression testing.
  • Overall, API testing is a valuable tool for ensuring the quality and reliability of an application, and can help to reduce the cost and time required to test an application.

protocols used in API testing?

There are several protocols that can be used in API testing:

  • HTTP (Hypertext Transfer Protocol): HTTP is the most commonly used protocol for API testing, as it is the standard protocol for communication on the World Wide Web. HTTP is a request-response protocol, which means that a client sends a request to a server and the server sends back a response.
  • HTTPS (HTTP Secure): HTTPS is a secure version of HTTP that uses Transport Layer Security (TLS) to encrypt data transmitted between a client and a server. HTTPS is often used for API testing when security is a concern, as it helps to prevent unauthorized access to data.
  • SOAP (Simple Object Access Protocol): SOAP is a protocol for exchanging information in the form of messages over the internet, using XML as the message format. SOAP APIs are often used in enterprise environments to provide a secure, reliable way for different systems to communicate with each other.
  • gRPC (Google Remote Procedure Call): gRPC is a high-performance, open-source remote procedure call (RPC) framework that uses HTTP/2 and Protocol Buffers (a binary serialization format) to transmit data. gRPC APIs are often used in microservices architectures to allow different services to communicate with each other.
  • WebSocket: WebSocket is a protocol that allows for full-duplex communication between a client and a server over a single TCP connection. WebSocket APIs can be used for real-time communication and are often used in chat applications, gaming, and other types of applications where low latency is important.
  • The choice of protocol for API testing will depend on the needs of the API and the systems that will be using it.

What is test environment of API?

  • The test environment for an API is the environment in which API testing is performed. It typically consists of the hardware and software components that are required to test the API, including the API itself, the test tools and frameworks that will be used, and any dependencies or supporting systems that are needed.
  • The test environment should be set up to closely match the production environment in which the API will be used, in order to accurately test the API's behavior and performance. This may involve setting up a test server or servers, configuring network infrastructure, and installing any required software or libraries.
  • It is important to carefully set up the test environment for API testing, as the quality and reliability of the test results will depend on it. If the test environment is not configured correctly, it could lead to inaccurate or misleading test results, which could compromise the integrity of the testing process.

What are the common API testing types?

There are several common types of API testing:

  • Functional testing: This type of testing is used to verify that the API is functioning correctly and is able to perform the operations it was designed to perform. This may include testing the API's input and output, as well as its error handling.
  • Load testing: This type of testing is used to evaluate the API's performance under a heavy load, such as a large number of concurrent requests. Load testing helps to ensure that the API can handle the expected level of traffic and can identify any performance bottlenecks.
  • Security testing: This type of testing is used to evaluate the security of the API and ensure that it is resistant to attacks or unauthorized access. This may include testing the API's authentication and authorization mechanisms, as well as its ability to handle invalid or malicious input.
  • Compatibility testing: This type of testing is used to ensure that the API is compatible with different systems and environments. This may include testing the API on different platforms or with different versions of software.
  • Usability testing: This type of testing is used to evaluate the usability of the API and ensure that it is easy to use and understand. This may include testing the API's documentation and other user-facing components.
  • Overall, the types of API testing that are performed will depend on the needs of the API and the systems that will be using it.

What must be checked when performing API testing?

There are several factors that should be checked when performing API testing:

  • Functionality: The API should be tested to ensure that it is able to perform the operations it was designed to perform, and that it returns the expected results. This may include testing the API's input and output, as well as its error handling.
  • Performance: The API should be tested to ensure that it performs well under different conditions, such as a heavy load or high concurrency. This may include load testing and stress testing the API.
  • Security: The API should be tested to ensure that it is secure and resistant to attacks or unauthorized access. This may include testing the API's authentication and authorization mechanisms, as well as its ability to handle invalid or malicious input.
  • Compatibility: The API should be tested to ensure that it is compatible with different systems and environments. This may include testing the API on different platforms or with different versions of software.
  • Usability: The API should be tested to ensure that it is easy to use and understand, and that its documentation is accurate and helpful.
  • Overall, it is important to thoroughly test the API to ensure that it is reliable, efficient, and meets the needs of the systems that will be using it.

What are differences between API Testing and Unit Testing?

  • API testing and unit testing are two different types of software testing that are used at different stages of the development process.
  • Unit testing is a type of testing that is used to test individual units of code, such as functions or methods, in isolation from the rest of the application. Unit tests are typically written by developers as they are writing code, and are used to validate the behavior of the code at the lowest level.
  • API testing, on the other hand, is a type of testing that is used to test the functionality of an application programming interface (API). API tests are typically performed at the integration level, and are used to validate the functional behavior of the API and ensure that it is reliable, efficient, and secure.
  • One key difference between API testing and unit testing is the level of abstraction at which they are performed. Unit tests are focused on testing the behavior of individual units of code, while API tests are focused on testing the behavior of the API as a whole.
  • Another difference is the scope of the tests. Unit tests are typically smaller in scope, as they are focused on testing individual units of code. API tests, on the other hand, may be broader in scope, as they are concerned with testing the API's overall behavior and integration with other systems.

What are common API errors that often founded?

There are several common errors that may be found when performing API testing:

  • 400 Bad Request: This error indicates that the request sent to the API was invalid or could not be understood by the server.
  • 401 Unauthorized: This error indicates that the request requires authentication, but the authentication provided was invalid or missing.
  • 403 Forbidden: This error indicates that the server understands the request, but refuses to authorize it.
  • 404 Not Found: This error indicates that the requested resource could not be found on the server.
  • 500 Internal Server Error: This error indicates that an unexpected condition was encountered by the server and no specific message was given.
  • 502 Bad Gateway: This error indicates that the server received an invalid response from an upstream server.
  • 503 Service Unavailable: This error indicates that the server is currently unable to handle the request due to maintenance or capacity issues.
  • These are just a few examples of common API errors that may be found during testing. There are many other possible errors that may be encountered, depending on the specific API and the circumstances of the test.

What kinds of bugs that API testing would often find?

API testing can be used to identify a wide variety of bugs in an application, including:

  • Functional bugs: These are bugs that affect the functionality of the API, such as issues with input or output, or problems with error handling.
  • Performance bugs: These are bugs that affect the performance of the API, such as issues with response times or capacity.
  • Security bugs: These are bugs that affect the security of the API, such as vulnerabilities that could be exploited by attackers.
  • Compatibility bugs: These are bugs that affect the compatibility of the API with different systems or environments.
  • Usability bugs: These are bugs that affect the usability of the API, such as issues with the API's documentation or other user-facing components.
  • Overall, API testing can be used to identify a wide variety of bugs in an application, and is an important tool for ensuring the quality and reliability of the API.

What is API documentation?

  • API documentation is a set of documentation that describes the functionality of an application programming interface (API). It is typically provided to developers who want to use the API in their own applications, and includes information about how to make requests to the API, what parameters are required or optional, and what kind of response to expect.
  • API documentation is an important tool for developers, as it helps them understand how to use the API and integrate it into their own applications. Good API documentation should be clear, concise, and easy to understand, and should include examples of how to use the API.
  • API documentation can be provided in a variety of formats, such as HTML, PDF, or Markdown. It is often made available on the API provider's website, or may be included as part of the API's codebase.
  • Overall, API documentation is an essential part of the API development process, as it helps developers understand how to use the API and ensure that it is integrated into their applications correctly.

What are API documentation templates that are commonly used?

There are several API documentation templates that are commonly used:

  • OpenAPI (formerly known as Swagger): OpenAPI is a widely used API documentation template that uses a JSON or YAML file to describe the API's functionality. OpenAPI allows developers to describe the API's endpoints, parameters, and responses, and provides tools for generating API documentation and interactive API consoles.
  • RAML (RESTful API Modeling Language): RAML is a specification for describing RESTful APIs. It uses a YAML file to describe the API's resources, methods, and responses, and provides tools for generating API documentation and testing APIs.
  • API Blueprint: API Blueprint is a specification for describing APIs using Markdown. It provides a simple, human-readable syntax for describing the API's resources, methods, and responses, and includes tools for generating API documentation and testing APIs.
  • Postman: Postman is a tool that allows developers to design, document, and test APIs. It includes a documentation template that allows developers to describe the API's endpoints, parameters, and responses, and provides tools for generating API documentation and interactive API consoles.
  • Overall, the choice of API documentation template will depend on the needs of the API and the preferences of the development team.

What is REST?

  • REST (Representational State Transfer) is an architectural style for creating web APIs. It is based on a set of principles that describe how resources should be exposed and accessed over the internet.
  • REST APIs use the HTTP protocol to send and receive data, and rely on the use of HTTP methods (such as GET, POST, PUT, and DELETE) to perform operations on resources that are identified using a URI (Uniform Resource Identifier). REST APIs are typically stateless, meaning that each request is independent and does not depend on the state of the server or previous requests.
  • REST is a popular architectural style for creating web APIs, as it is simple to use and can be implemented using any programming language. REST APIs are often used to expose data or functionality to be consumed by other systems or applications over the internet.

What is a RESTFul Web Services?

  • RESTful web services are web services that are built using the REST architectural style. RESTful web services expose a set of resources that can be accessed over the internet using standard HTTP methods (such as GET, POST, PUT, and DELETE). Each resource is identified using a URI (Uniform Resource Identifier), and the resource's representation (such as HTML, XML, or JSON) can be accessed using the HTTP methods.
  • RESTful web services are designed to be lightweight and easy to use, and are often used to expose data or functionality to be consumed by other systems or applications over the internet. They are typically stateless, meaning that each request is independent and does not depend on the state of the server or previous requests.
  • RESTful web services are a popular choice for building web APIs, as they are simple to implement and can be used with any programming language. They are often used in microservices architectures, where they are used to enable communication between different services.

Which protocol is used by RESTful Web services? and why ?

  • RESTful web services typically use the HTTP protocol to send and receive data. HTTP (Hypertext Transfer Protocol) is a widely used application-level protocol that is designed to enable communication between clients and servers on the World Wide Web.
  • HTTP is a request-response protocol, which means that a client sends a request to a server and the server sends back a response. HTTP uses a simple, human-readable syntax for sending and receiving data, and is supported by most web browsers and servers.
  • HTTP is used by RESTful web services because it is simple, widely supported, and well-suited to the needs of web APIs. RESTful web services use the HTTP methods (such as GET, POST, PUT, and DELETE) to perform operations on resources that are identified using a URI (Uniform Resource Identifier). HTTP is also used to transmit the data representation of the resources (such as HTML, XML, or JSON) between the client and the server.
  • Overall, the use of HTTP makes it easy for RESTful web services to expose resources and enable communication over the internet.

What is messaging in RESTful Web services?

  • Messaging in RESTful web services refers to the exchange of data between the client and the server using the HTTP protocol. When a client sends a request to a RESTful web service, it is sending a message to the server. The server processes the request and sends back a response, which is also a message.
  • In RESTful web services, the messages are typically in the form of HTTP requests and responses. The request message includes information about the request, such as the HTTP method (e.g. GET, POST, PUT, DELETE), the URI of the resource being requested, and any data or parameters that are required to process the request. The response message includes information about the response, such as the status code and the data representation of the resource (such as HTML, XML, or JSON).
  • Overall, messaging is a key aspect of RESTful web services, as it enables communication and the exchange of data between the client and the server using the HTTP protocol.

What are the core components of an HTTP request?

  • An HTTP request consists of several core components:
  • Method: The method specifies the action that the request is intended to perform. Common HTTP methods include GET, POST, PUT, and DELETE.
  • URI: The URI (Uniform Resource Identifier) specifies the location of the resource that the request is targeting.
  • Headers: The headers contain metadata about the request, such as the content type and encoding, the user agent, and any cookies that are associated with the request.
  • Body: The body of the request contains the data that is being sent to the server. The body is optional and is not included in all types of requests.
  • Overall, these are the core components of an HTTP request. The specific format of the request will depend on the HTTP version and the type of request being made.

What is Basic Authentication in Web API?

  • Basic Authentication is a method for an HTTP user agent, such as a web browser, to provide a user name and password when making a request to the server. The user name and password are encoded and sent in the header of the HTTP request.
  • Here's an example of how a request using Basic Authentication might look:
    GET /resource HTTP/1.1
    Host: example.com
    Authorization: Basic Zm9vOmJhcg==
    
    In this example, the word "Basic" indicates that the request is using Basic Authentication. The string Zm9vOmJhcg== is the base64-encoded version of the user name foo and the password bar.
  • Basic Authentication is simple and easy to implement, but it has a number of limitations. For example, the user name and password are sent in every request, so it is not well suited for scenarios where the user needs to authenticate frequently. In addition, Basic Authentication does not provide any confidentiality for the transmitted credentials, as they are sent in plain text.

What is API Key Authentication in Web API?

  • API Key Authentication is a method for authenticating API requests based on the presence of a pre-agreed API key. The API key is a unique identifier that is passed in the API request header, and is used to identify the API client and authorize access to the API.
  • Here's an example of how a request using API Key Authentication might look:
    GET /resource HTTP/1.1
    Host: example.com
    API-Key: abcdefghijklmnopqrstuvwxyz
    
    In this example, the API-Key header contains the API key abcdefghijklmnopqrstuvwxyz. The server can then use this key to look up the API client's details and authorize the request.
  • API Key Authentication has a number of benefits. It is simple to implement and does not require the client to send any sensitive information, such as a user name or password, with the request. In addition, API keys can be easily revoked if necessary, which makes it easy to manage access to the API.
  • However, API Key Authentication does have some limitations. For example, it does not provide any way to authenticate the API client, so it is not suitable for scenarios where the client needs to be authenticated. In addition, API keys can be easily compromised, so it is important to use them in conjunction with other security measures, such as rate limiting and IP whitelisting.

What is Token based authentication?

  • Token-based authentication is a method of authenticating a user by using a token. The token is a unique identifier that is generated by the server and sent to the client. The client then includes the token in each subsequent request to the server to authenticate itself.
  • There are several different ways that token-based authentication can be implemented. One common method is to use JSON Web Tokens (JWTs). JWTs are self-contained and can be signed and encrypted to provide secure authentication and authorization.
  • Here's an example of how a request using JWT-based authentication might look:
    GET /resource HTTP/1.1
    Host: example.com
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
    
    
    In this example, the Authorization header contains the string Bearer followed by the JWT. The JWT consists of three parts: a header, a payload, and a signature. The header and payload are base64-encoded and the signature is generated using the header and payload and a secret key known only to the server. Token-based authentication has a number of benefits. It allows the server to authenticate the client without the need to send sensitive information, such as a user name or password, with each request. In addition, tokens can be easily revoked if necessary, which makes it easy to manage access to the API.
  • However, token-based authentication does have some limitations. For example, it requires the client to store and transmit the token with each request, which can increase the complexity of the client implementation. In addition, tokens can be compromised if they are not properly secured, so it is important to use strong encryption and secure storage for the tokens.

What is OAuth?

  • OAuth (Open Authorization) is an open standard for authorization that allows a user to grant a third-party application access to their resources without sharing their credentials. It provides a secure way for a user to authorize a client to access their resources on a server, without the client needing to know the user's credentials.
  • OAuth is often used to allow users to log in to a third-party application using their existing account on a different service, such as their Google account or their Facebook account.
  • Here's an example of how the OAuth authorization process might work: The user logs in to the third-party application and wants to access a protected resource on a server.
  • The third-party application redirects the user to the server's authorization endpoint.
  • The user logs in to the server and grants the third-party application permission to access their resources.
  • The server redirects the user back to the third-party application with an authorization code.
  • The third-party application exchanges the authorization code for an access token.
  • The third-party application uses the access token to access the protected resource on the server.
  • OAuth has a number of benefits. It allows users to grant access to their resources without sharing their credentials, and it provides a secure and standard way for applications to access resources on behalf of a user. However, it can be complex to implement, as it involves multiple steps and interactions between the client, the user, and the server.

What is JWT Authentication?

  • JSON Web Token (JWT) is a method for securely transmitting information between parties. It is often used for authentication and authorization, and is widely supported by web APIs.
  • In the context of authentication and authorization, a JWT is typically used to transmit a user's identity and other claims between two parties. For example, when a user logs in to a web application, the application might generate a JWT that contains the user's identity and other claims, such as the user's name and roles. The application can then send the JWT to the user, who can include it in subsequent requests to the application to authenticate themselves.
  • Here's an example of how a JWT might look:
  • eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c A JWT consists of three parts: a header, a payload, and a signature. The header and payload are base64-encoded and the signature is generated using the header and payload and a secret key known only to the server.
  • JWT-based authentication has a number of benefits. It allows the server to authenticate the client without the need to send sensitive information, such as a user name or password, with each request. In addition, JWTs are self-contained and can be signed and encrypted to provide secure authentication and authorization. However, JWT-based authentication does have some limitations. For example, it requires the client to store and transmit the JWT with each request, which can increase the complexity of the client implementation. In addition, JWTs can be compromised if they are not properly secured, so it is important to use strong encryption and secure storage for the JWTs.

What are the parts of JWT token?

  • A JSON Web Token (JWT) consists of three parts: a header, a payload, and a signature.
  • The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
  • The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims. Registered claims are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of the registered claims are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.
  • The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.
  • Here is an example of a JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c In this example, the first part of the JWT (before the period) is the base64-encoded header, the second part (between the periods) is the base64-encoded payload, and the third part (after the second period) is the signature.

Where JWT token reside in the request?

  • In a request, a JSON Web Token (JWT) is typically sent in the Authorization header. The Authorization header is used to pass authentication information to the server, and it is typically used in conjunction with HTTP Basic Authentication or HTTP Token Authentication.
  • Here's an example of how a request with a JWT might look:
    GET /resource HTTP/1.1
    Host: example.com
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
    
    
    In this example, the Authorization header contains the string Bearer followed by the JWT. The server can then use the JWT to authenticate the user.
  • Alternatively, a JWT can be sent as a query parameter or in a cookie. However, sending a JWT in the Authorization header is the most common and secure way to transmit a JWT.

What are main Return Types supported in Web API?

Web APIs can return data in a variety of formats, depending on the needs of the client and the design of the API. Some of the most common return types are:

  • application/json: This is the most common return type for web APIs, as it is easy to work with and supported by a wide range of clients. When an API returns data in JSON format, the data is serialized as a JSON object and sent in the body of the HTTP response.
  • text/plain: This return type is used for simple, unformatted text. It is often used for debugging or for returning simple messages to the client.
  • application/xml: This return type is used for data serialized as XML. It is less common than application/json, as JSON is generally easier to work with.
  • application/octet-stream: This return type is used for binary data, such as a file download. It is often used in conjunction with the Content-Disposition header, which specifies the file name and other information about the download.
  • application/pdf: This return type is used for data in PDF format. It is often used for returning documents or reports to the client.
  • These are just a few examples of the return types that can be used in a web API. Other return types are also possible, depending on the needs of the client and the capabilities of the API.

What is the difference between HTTPResponseMessage and IHttpActionResult?

  • HttpResponseMessage is a class in the System.Net.Http namespace that represents an HTTP response message. It is often used to return custom HTTP responses from a Web API action.
  • IHttpActionResult is an interface in the System.Web.Http namespace that represents the result of an action that returns an HTTP response message. It is often used to return a standard HTTP response, such as a 200 OK or a 404 Not Found, from a Web API action.
  • One of the main differences between HttpResponseMessage and IHttpActionResult is that IHttpActionResult abstracts the creation of the HttpResponseMessage and allows the action to return a simple value or object, rather than the HttpResponseMessage itself. This can make it easier to write and test Web API actions, as it decouples the action from the details of creating the HttpResponseMessage.
  • Here's an example of how HttpResponseMessage might be used in a Web API action:
        
    public HttpResponseMessage Get()
    {
        var value = "hello, world";
        return new HttpResponseMessage()
        {
            Content = new StringContent(value),
            StatusCode = HttpStatusCode.OK
        };
    }
    
    And here's an example of how IHttpActionResult might be used in a Web API action:
    public IHttpActionResult Get()
    {
        var value = "hello, world";
        return Ok(value);
    }
    
    In the IHttpActionResult example, the action returns a value directly, and the framework takes care of creating the HttpResponseMessage and setting the appropriate status code. This can make the action easier to write and test, as it does not need to know the details of creating the HttpResponseMessage.

What is MediaTypeFormatter class in Web API?

  • The MediaTypeFormatter class is a base class in the System.Net.Http.Formatting namespace that represents a formatter that can read and write a specific media type. In the context of a Web API, a MediaTypeFormatter is used to convert the request and response data to and from the serialized format that is transmitted over the wire.
  • Web API includes several built-in MediaTypeFormatter classes, such as JsonMediaTypeFormatter and XmlMediaTypeFormatter, which can be used to serialize and deserialize data in JSON and XML format, respectively.
  • You can also create your own custom MediaTypeFormatter classes if you need to support a different serialization format or if you need to customize the way that data is serialized or deserialized.
  • Here's an example of how you might use a MediaTypeFormatter in a Web API action:
    public HttpResponseMessage Get()
    {
        var value = "hello, world";
        var formatter = new JsonMediaTypeFormatter();
        var content = new ObjectContent(value, formatter);
        return new HttpResponseMessage()
        {
            Content = content,
            StatusCode = HttpStatusCode.OK
        };
    }
    
    In this example, the JsonMediaTypeFormatter is used to serialize the value string as JSON and add it to the HttpResponseMessage. The HttpResponseMessage is then returned to the client with the appropriate status code. You can also use MediaTypeFormatter classes to deserialize request data in a Web API action. For example:
  • public HttpResponseMessage Post([FromBody] string value)
    {
        // value will be deserialized from the request body using the appropriate MediaTypeFormatter
        return new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK
        };
    }
    
    In this example, the value parameter will be deserialized from the request body using the appropriate MediaTypeFormatter, based on the Content-Type header of the request.

What are Response Codes in Web API?

HTTP response codes are status codes that are returned by a server to indicate the status of a request. In the context of a Web API, response codes are used to indicate the result of an API request and to provide additional information about the request. Here are some common HTTP response codes that you might see in a Web API:

  • 200 OK: This response code indicates that the request was successful and that the requested resource was found.
  • 201 Created: This response code indicates that the request was successful and that a new resource was created as a result of the request.
  • 204 No Content: This response code indicates that the request was successful, but there is no additional information to send back.
  • 400 Bad Request: This response code indicates that the request was invalid or cannot be processed.
  • 401 Unauthorized: This response code indicates that the request requires authentication.
  • 403 Forbidden: This response code indicates that the server understands the request, but it refuses to authorize it.
  • 404 Not Found: This response code indicates that the requested resource was not found.
  • 500 Internal Server Error: This response code indicates that an unexpected condition was encountered by the server and no more specific message is suitable.
  • These are just a few examples of the HTTP response codes that can be used in a Web API. There are many other response codes that can be used to provide more information about the status of a request.

Best Wishes by:- Code Seva Team