Introduction To APIs and API Testing
Introduction To APIs and API Testing
A
End to End API Testing
hapter 1
C
urated By:
C
Introduction to APIs and API Testing
Lamhot Siagian
TABLE OF CONTENTS
2
Introduction to APIs and API Testing, Curated by Lamhot Siagian
Chapter 1
Understanding APIs
PIs (Application Programming Interfaces) is fundamental for modern software development, as they
A
enabledifferentsoftwaresystemstocommunicatewitheachother.Here’sadetailedoverviewtohelpyou
understand what APIs are, how they work, and why they are important.
What is an API?
An API, or application programming interface, is a set of rules or protocols that enables software
pplications to communicate with each other to exchange data, features and functionality..
a
simple way to understand how APIs work is to look at a common example—third-party payment
A
processing.Whenauserpurchasesaproductonane-commercesite,thesitemightprompttheuserto“Pay
with PayPal” or another type of third-party system. This function relies on APIs to make the connection.
- hen the buyer clicks the payment button, an APIcallissenttoretrieveinformation.Thisisthe
W
request.ThisrequestisprocessedfromanapplicationtothewebserverthroughtheAPI’sUniform
Resource Identifier (URI) and includes a request verb, headers, and sometimes, a request body.
- Afterreceivingavalidrequestfromtheproductwebpage,theAPIcallstotheexternalprogramor
web server, in this case, the third-party payment system.
- The server sends a response to the API with the requested information.
- The API transfers the data to the initial requesting application, in this case, the product website1
Components of an API
.
1 ndpoints: URLs that provide access to specific resourcesor functionalities.
E
2. Methods/HTTP Verbs: Actions that can be performed(e.g., GET, POST, PUT, DELETE).
3. Requests: Data sent by the client to the server.
4. Responses: Data sent back by the server to the client.
1
https://www.ibm.com/topics/api
1
Introduction to APIs and API Testing, Curated by Lamhot Siagian
. H
5 eaders: Metadata about the request or response (e.g., authentication tokens, content type).
6. Payload/Body: Data being sent with the request (typicallyin JSON or XML format).
.
1 utomation: Streamlines repetitive tasks, boostingproductivity.
A
2. Innovation: Enables external teams to innovate byleveraging existing functionalities.
3. Security: Adds a layer of protection by requiringauthentication and authorization.
4. Cost Efficiency: Reduces expenses by using third-party tools instead of developing in-house
systems.2
1. I ntegration: Connecting different applications andservices, such as integrating payment gateways
into e-commerce platforms.
2. Automation: Automating repetitive tasks, such as deployingcode, managing resources, or data
synchronization.
3. Data Access: Providing access to data from differentsources, such as retrieving weather data or
financial information.
4. Third-Party Services: Enabling third-party developersto build applications that interact with your
services, such as social media apps using Facebook or Twitter APIs.
5. Microservices Architecture: Facilitating communicationbetween microservices in a distributed
system.
API Documentation
ood API documentation is essential for developers to understand how to use the API effectively. It
G
typically includes:
.
1 ndpoint Descriptions: Detailed information aboutavailable endpoints and their purposes.
E
2. HTTP Methods: The methods supported by each endpoint(e.g., GET, POST).
3. Parameters: Required and optional parameters for eachendpoint.
4. Request and Response Formats: Examples of requestpayloads and expected responses.
5. Authentication: Information about authentication andauthorization mechanisms.
6. Error Handling: Common error codes and messages, along with troubleshooting information.
2
https://www.postman.com/what-is-an-api/#benefits-of-apis
2
Introduction to APIs and API Testing, Curated by Lamhot Siagian
PI testing is a crucial aspect of software development, offering numerous benefits and addressing key
A
challenges that can significantly impact the quality, reliability, andperformanceofsoftwareapplications.
Here are the primary reasons why API testing is important:
● V erification of Requirements: API testing ensuresthat the API functions according to the specified
requirements. This involves checking that the endpoints are working correctly, the data is being
processed as expected, and the correct responses are returned.
● Detection of Errors Early: By testing APIs early inthe development cycle, errors can be detected
and fixed before they become more difficult and costly to resolve.
● C onsistent Performance: Regular API testing helpsensure that the API performs consistently
under various conditions, reducing the likelihood of unexpected failures in production
environments.
● Regression Testing: API tests can be automated andincluded in regression testing to ensure that
new changes do not break existing functionality.
● I dentification of Vulnerabilities: API testing canreveal security vulnerabilities such as SQL
injection, cross-site scripting (XSS), and other common exploits.
● Validation of Authentication and Authorization: Ensuresthat security mechanisms like
authentication and authorization are working correctly, protecting sensitive data and functionality
from unauthorized access.
● L oad and Stress Testing: API testing includes performancetests such as load and stress testing,
which help determine how well the API performs under heavy traffic and identify potential
bottlenecks.
● Scalability Assessment: Helps in assessing whetherthe API can scale effectively to handle
increased load as the user base grows.
● E nsures Smooth Integration: For APIs that are consumedby external developers or third-party
applications, thorough testing ensures that these integrations work smoothly, providing a better
user experience.
● Reduces Downtime: By identifying and resolving issuesearly, API testing helps reduce the chances
of downtime, ensuring that end-users experience fewer disruptions.
3
Introduction to APIs and API Testing, Curated by Lamhot Siagian
● A utomated Testing: API tests can be automated and integrated into CI/CD pipelines, providing
quick feedback to developers and ensuring that changes do not introduce new issues.
● Continuous Monitoring: Ongoing API testing helps monitor the API's health and performance
continuously, allowing for rapid response to issues.
● I mproved Debugging: API tests provide detailed informationabout failures, making it easier for
developers to debug and resolve issues.
● Documentation and Clarity: Writing API tests oftenhelps clarify the API's functionality and
expected behavior, which can improve the quality of documentation and assist other developers in
understanding how to use the API.
● L ower Maintenance Costs: Identifying and fixing issues early in the development process reduces
the costs associated with post-release maintenance and support.
● Fewer Production Issues: Well-tested APIs are lesslikely to cause issues in production, leading to
reduced costs related to bug fixes and customer support.
● A dherence to Standards: API testing ensures that theAPI complies with industry standards and
protocols, which is particularly important for APIs in regulated industries.
● Contract Testing: Validates that the API contracts(the agreed-upon schema and behavior between
API consumers and providers) are maintained, ensuring compatibility and reliability.
4
Introduction to APIs and API Testing, Curated by Lamhot Siagian
Types of APIs
PIscomeinvariousforms,eachwithitsownstrengthsandpurposes.Understandingthesedifferencesis
A
essentialforpickingtherightAPIforyourprojectandensuringyourapplicationiseffective,scalable,and
reliable.Let’slookatthedifferenttypesofAPIs,exploringwhatmakeseachuniqueandhowtheyfitinto
modern software development.
This table provides a high-level overview of various API types, their descriptions, and examples.3
ibrary-based
L art of software libraries,
P J ava API for Android app development, .NET
APIs language-specific, range from basic libraries used in Windows applications
utilities to complex GUI components
perating
O rovide interfaces for OS interaction,
P indows API for Windows OS interaction,
W
system APIs manage hardware resources and POSIX API for UNIX-like systems
processes
Database APIs E
nable interaction with database QL API for relational databases, Oracle’s
S
management systems, facilitate data OCI for Oracle databases
querying and manipulation
ardware
H llow communication with hardware
A I oT device APIs for smart home systems,
APIs devices, direct control over hardware Printer APIs for document processing
functions
TTP APIs
H acilitate client-server communication W
F eb services, mobile apps, IoT devices, social
(web API) over the web, use standard HTTP media platforms, content management
methods, lightweight and flexible systems
EST APIs
R se HTTP requests for data
U eb services accessible via the web, social
W
(web API) operations, stateless and separate media APIs, cloud services
client-server concerns
OAP APIs
S se service interfaces to expose
U nterprise-level services like banking,
E
(web API) business logic, high security, suitable healthcare, where security and transactions
for enterprise-level organizations are critical
raphQL
G lients request only needed data,
C omplex data-driven web and mobile
C
APIs (web reduce data transfer over the network, applications, ad-hoc queries by the client
API) support multiple responses in one
request
3
https://www.nylas.com/api-guide/types-of-apis/
5
Introduction to APIs and API Testing, Curated by Lamhot Siagian
pen APIs
O ccessible by third-party developers,
A witter API for tweets, Stripe API for
T
(public APIs) typically for external users, require payments, providing data or services to
API keys external developers
omposite
C ombine different data and service
C ggregating various services in a single call
A
APIs APIs, access multiple endpoints in one for smoother user experience, commonly used
call in microservices architectures
ynchronous
S ynchronous: Request-response
S ynchronous: Essential data retrieval, web
S
and model, Asynchronous: Non-blocking, page loading, Asynchronous: Background
asynchronous no immediate response required tasks, real-time data streams
ibrary-based
L art of software libraries,
P J ava API for Android app development, .NET
APIs language-specific, range from basic libraries used in Windows applications
utilities to complex GUI components
6
Introduction to APIs and API Testing, Curated by Lamhot Siagian
O
● bjective: Test individual API components in isolation.
● Tools: JUnit (Java), NUnit (C#), pytest (Python).
● Description: Unit tests are typically written by developersto test the functionality of specific
methods or functions in the API, ensuring that each part works as intended.
O
● bjective: Verify that the API performs its intendedfunctions correctly.
● Tools: Postman, SoapUI, REST Assured.
● Description: Functional tests validate the API againstthe functional requirements and
specifications. This includes testing endpoints, methods (GET, POST, PUT, DELETE), and responses.
O
● bjective: Ensure that the API interacts correctly with other components and systems.
● Tools: Postman, SoapUI, JUnit (with integration test configurations).
● Description: Integration tests evaluate the interactions between different parts of the API and other
services or databases to ensure that integrated parts work together as expected.
O
● bjective: Assess the API’s performance under variousconditions.
● Tools: JMeter, LoadRunner, Gatling.
● Description: Performance tests include load testing (to check API behavior under expected load),
stress testing (to determine the API’s breaking point), and endurance testing (to evaluate
performance over an extended period).
O
● bjective: Identify vulnerabilities and ensure the API is secure.
● Tools: OWASP ZAP, Burp Suite, Postman (with securityextensions).
● Description: Security testing involves checking forcommon vulnerabilities like SQL injection,
cross-site scripting (XSS), and ensuring proper authentication and authorization mechanisms are in
place.
O
● bjective: Ensure the API is easy to use and well-documented.
● Tools: Swagger, Postman.
● Description: Usability testing focuses on the API’s user experience, ensuring that the
documentation is clear, the endpoints are intuitive, and error messages are helpful.
7
Introduction to APIs and API Testing, Curated by Lamhot Siagian
O
● bjective: Validate the API’s functionality, performance,and security comprehensively.
● Tools: Postman, SoapUI.
● Description: Validation testing ensures that the API meets the business requirements and
expectations, combining functional, performance, and security testing aspects.
O
● bjective: Ensure the API complies with industry standardsand regulations.
● Tools: Postman, SoapUI, custom scripts.
● Description: Compliance testing checks if the APIadheres to legal and regulatory requirements,
such as GDPR, HIPAA, and other industry-specific standards.
O
● bjective: Test the API in isolated environments bysimulating dependencies.
● Tools: WireMock, MockServer, Postman (mock servers).
● Description: Mocking and virtualization allow testers to simulate the behavior of the API’s
dependencies, enabling testing in scenarios where real dependencies are unavailable or difficult to
configure.
O
● bjective: Ensure new changes do not negatively affectexisting functionality.
● Tools: Postman, SoapUI, automated test scripts.
● Description: Regression testing involves re-running previously conducted tests to verify that new
code changes have not introduced any new bugs or issues.
● utomation: Automate as many tests as possible to ensure efficiency and repeatability.
A
● Version Control: Keep track of API versions and ensuretests are updated accordingly.
● Environment Management: Use consistent environmentsfor testing to avoid discrepancies.
● Data Management: Use realistic data for testing touncover potential issues.
● Continuous Integration/Continuous Deployment (CI/CD):Integrate API testing into the CI/CD
pipeline to catch issues early.
8
Introduction to APIs and API Testing, Curated by Lamhot Siagian
2. Can you explain the difference between REST and SOAP APIs?
Answer:
3. What are the main HTTP methods used in RESTful APIs and what are their purposes?
Answer:
● ET: Retrieve data from the server.
G
● POST: Submit data to the server to create a new resource.
● PUT: Update an existing resource on the server.
● DELETE: Remove a resource from the server.
● PATCH: Apply partial modifications to a resource.
nswer:AnAPIendpointisaspecificURLthatprovidesaccesstoaparticularresourceorfunctionalityof
A
theAPI.ItrepresentsoneofthediscreteunitsofinteractioninanAPIandistypicallyacombinationofthe
base URL and a resource path.
9
Introduction to APIs and API Testing, Curated by Lamhot Siagian
s ession information about the client between requests, making each request independent and
self-contained.
nswer:AnAPIkeyisauniqueidentifierusedtoauthenticateaclientaccessinganAPI.Ithelpstrackand
A
control how the API is used, ensuring that only authorized users can make requests. API keys are
commonly used for security purposes to prevent misuse and limit the number of requests from a client.
nswer: CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to
A
preventwebpagesfrommakingrequeststoadifferentdomainthantheonethatservedthewebpage.Itis
important in webAPIsbecauseitenablesserverstospecifywhocanaccesstheirresources,ensuringthat
only trusted domains can make cross-origin requests.
8. What are some common status codes returned by APIs, and what do they mean?
Answer:
● 00 OK: The request was successful.
2
● 201 Created: A new resource was successfully created.
● 204 No Content: The request was successful, but there is no content to return.
● 400 Bad Request: The request was invalid or cannot be processed.
● 401 Unauthorized: Authentication is required and hasfailed or not been provided.
● 403 Forbidden: The server understands the request but refuses to authorize it.
● 404 Not Found: The requested resource could not befound.
● 500 Internal Server Error: An error occurred on the server side.
9. What is the purpose of API versioning and how can it be implemented?
nswer:APIversioningensuresthatchangesintheAPIdonotbreakexistingclientapplications.Itallows
A
developers to introduce new features andimprovementswithoutdisruptingthecurrentfunctionalityfor
existing users. Versioning can be implemented in several ways:
/v1/users
● URL Path: Including the version number in the URL(e.g., ).
?version=1
● Query Parameters: Adding a version parameter in thequery string (e.g., ).
Accept:
● Headers: Using a custom header to specify the version (e.g.,
application/vnd.myapi.v1+json
).
10. What are the differences between synchronous and asynchronous API calls?
Answer:
10
Introduction to APIs and API Testing, Curated by Lamhot Siagian
T
○ he client sends a request and waits for the server to respond.
○ The client is blocked until the response is received.
○ Simple and straightforward but can lead to inefficiencies if the server takes a long time to
respond.
Asynchronous API Calls:
●
○ The client sends a request and continues processing other tasks.
○ The client is notified (usually via a callback or promise) when the response is ready.
○ More efficient for long-running operations, as it doesn't block the client.
Answer:RatelimitingisamechanismtocontrolthenumberofrequestsaclientcanmaketoanAPIwithin
certain time period. It is important for:
a
● P reventing Abuse: Protects the API from being overwhelmedby too many requests from a single
client.
● Ensuring Fair Usage: Ensures that all clients have fair access to the API.
● Maintaining Performance: Helps maintain the API'sperformance and availability by avoiding
excessive load.
nswer: API throttling is a technique used to control the usage of an API by limiting the number of
A
requests that can be made in aspecifictimeframe.Ithelpsinmanagingtheloadontheserver,ensuring
serviceavailability,andpreventingabuse.Throttlingcanbeimplementedbysettingalimitonthenumber
of requests per minute, hour, or day.
11