DocsStation
FastAPI

API Documentation: Complete Guide

By csestudy247 Updated December 2, 2026 15 min read
15 min read

API (Application Programming Interface) is a software intermediary that allows two or more applications to communicate with each other.

Instead of directly accessing another application’s database or internal code, applications communicate through predefined interfaces called APIs.

Simply put,

API acts as a messenger between two software systems.

For example,

  • Mobile App ↔ API ↔ Server
  • Website ↔ API ↔ Database
  • Payment App ↔ API ↔ Bank
  • Weather App ↔ Weather API
Restaurant Analogy: Understanding How an API Works The API acts like a waiter between the client and the backend server. 👤 Customer (Client / Frontend) 🤵 API (Waiter) Receives Request Validates Request Returns Response Does NOT Cook Food 🍳 Kitchen (Server / Backend) ① Customer Places Order ② API Sends Request ③ Kitchen Prepares Food ④ API Returns Response Restaurant ↔ API Mapping Customer = Client (Browser / Mobile App) Waiter = API Kitchen = Backend Server Pantry = Database Food Order = HTTP Request Food = JSON Response

Benefits of APIs Why APIs are the backbone of modern software development API Application Programming Interface 🔗 Integration Connect different applications ⚡ Faster Development Reuse existing services 🛡 Security Secure access with authentication 📈 Scalability Support millions of users ♻ Reusability One API serves many clients 💰 Cost Saving Reduce development effort

Types of APIs:

APIs (Application Programming Interfaces) are everywhere in modern software development. Whether you’re building a website, mobile app, machine learning model, or desktop application, you’re interacting with one or more APIs.

Different APIs serve different purposes. Some help applications communicate over the internet, while others provide access to databases, hardware devices, or software libraries.

In this guide, we’ll explore the six major types of APIs every developer should know.


1. Web API

A Web API is an API that allows applications to communicate with each other over the internet using the HTTP/HTTPS protocol. It is the most common type of API used in modern web and mobile applications.

Whenever you book a cab, check the weather, log in with Google, or make an online payment, your application is most likely communicating with one or more Web APIs.

Most Web APIs exchange data using JSON, although some older systems still use XML.

Key Features

  • Accessible over HTTP or HTTPS
  • Enables communication between different applications
  • Platform independent
  • Commonly returns data in JSON or XML
  • Can be consumed by web, mobile, desktop, and IoT applications

Real-World Examples

  • Getting live weather information from the OpenWeather API
  • Displaying locations using Google Maps API
  • Processing online payments with Stripe or Razorpay
  • Logging users in with Google OAuth APIs

2. Library API

A Library API provides developers with ready-made functions, classes, and methods that can be directly used inside a program.

Instead of writing complex algorithms from scratch, developers simply import a library and use its API.

Unlike Web APIs, Library APIs do not require an internet connection because they execute locally inside your application.

Key Features

  • Runs locally within your application
  • Provides reusable functions and classes
  • Improves developer productivity
  • Eliminates the need to reinvent common functionality

Example

Library APIDescriptionCommon Use Cases
NumPy APIProvides functions for mathematical and numerical computations such as arrays, linear algebra, statistics, and random number generation.Scientific computing, data analysis, machine learning
Pandas APIOffers powerful tools for data cleaning, filtering, grouping, merging, and analyzing structured datasets.Data preprocessing, data manipulation, ETL pipelines
TensorFlow APIProvides APIs to build, train, evaluate, and deploy machine learning and deep learning models.AI applications, computer vision, NLP, predictive analytics
Matplotlib APIEnables developers to create charts, graphs, and visualizations programmatically with extensive customization options.Data visualization, analytics dashboards, research reports

3. Remote API

A Remote API allows an application to communicate with another application running on a different computer, server, or network.

These APIs can operate over the public internet or a private organizational network (intranet).

An important point to remember is:

Every Web API is a Remote API, but not every Remote API is a Web API.

Some Remote APIs are only accessible inside private company networks and are never exposed to the public internet.

Key Features

  • Connects applications across different machines
  • Can operate over the internet or intranet
  • Enables distributed systems
  • Frequently used in cloud computing

Real-World Examples

  • AWS EC2 API for creating virtual machines
  • Google Drive API for accessing cloud files
  • Internal banking APIs available only inside company networks
  • Enterprise APIs connecting different internal systems

4. Database API

A Database API provides a structured way for applications to interact with databases.

Instead of writing low-level communication code, developers use database APIs to perform CRUD operations:

  • Create
  • Read
  • Update
  • Delete

Database APIs simplify data management while hiding implementation details.

Key Features

  • Performs CRUD operations
  • Supports SQL and NoSQL databases
  • Improves security through standardized interfaces
  • Simplifies database connectivity

Example

Database APIDescriptionCommon Use Cases
MySQL Connector APIEnables Python, Java, C#, and other programming languages to connect to MySQL databases and execute SQL queries.Web applications, enterprise systems, CRUD operations
MongoDB APIProvides methods to create, read, update, and delete (CRUD) documents in MongoDB collections.NoSQL databases, document storage, real-time applications
Firebase Realtime Database APIEnables real-time data synchronization across multiple clients, ensuring changes are instantly reflected in connected applications.Chat applications, collaborative apps, live dashboards, multiplayer games
PostgreSQL APIAllows applications to communicate with PostgreSQL databases for executing SQL queries, managing transactions, and performing CRUD operations.Enterprise applications, analytics platforms, financial systems


5. Hardware API

A Hardware API enables software applications to communicate directly with physical hardware devices.

Without Hardware APIs, developers would need to write complex low-level code for every hardware component.

These APIs provide a simple interface for controlling hardware and retrieving information from devices.

Key Features

  • Abstracts hardware complexity
  • Enables communication with physical devices
  • Supports high-performance computing
  • Common in robotics and IoT development

Example

Hardware APIDescriptionCommon Use Cases
CUDA APIEnables developers to program NVIDIA GPUs for high-performance parallel computing and accelerated processing.Deep learning, scientific computing, image processing, GPU acceleration
OpenCL APIProvides a framework for writing programs that execute across CPUs, GPUs, DSPs, and other heterogeneous processors.Parallel computing, cross-platform hardware acceleration, simulations
IoT Device APIsAllow applications to communicate with sensors, smart home devices, wearables, and industrial IoT equipment.Smart homes, healthcare monitoring, industrial automation, environmental sensing
Robotics APIsProvide interfaces to control robots, drones, robotic arms, and autonomous systems while accessing sensor and actuator data.Robotics, drone programming, warehouse automation, autonomous vehicles

6. GUI API

A GUI (Graphical User Interface) API helps developers build graphical applications without manually drawing interface elements.

Using GUI APIs, developers can create windows, buttons, menus, text boxes, images, and other interactive components.

These APIs are widely used in desktop and mobile application development.

Key Features

  • Creates graphical interfaces
  • Manages user interaction
  • Provides reusable UI components
  • Supports event-driven programming

Real-World Examples

GUI APIDescriptionCommon Use Cases
Java SwingA Java GUI toolkit that provides components such as windows, buttons, menus, and text fields for building desktop applications.Desktop software, business applications, educational tools
TkinterPython’s built-in GUI library used to create cross-platform desktop applications with minimal code.Python desktop applications, calculators, utility tools, learning projects
Android SDKProvides APIs, UI components, and development tools for building Android mobile application interfaces.Android apps, mobile games, business applications, e-commerce apps
JavaFXA modern Java framework for creating rich, interactive desktop applications with advanced UI controls, animations, and multimedia support.Enterprise desktop applications, dashboards, media players, data visualization tools

What is an API Protocol?

An API protocol defines the set of rules and standards that allow two applications to communicate with each other.

It specifies:

  • How requests are sent
  • How responses are returned
  • Data formats
  • Communication methods
  • Security mechanisms

Think of an API protocol as a common language that both the client and server understand.


1. REST (Representational State Transfer)

REST stands for Representational State Transfer. It is the most widely used architectural style for building Web APIs.

REST uses the HTTP protocol and represents resources using URLs. Every request from the client contains all the information needed to process it, making REST stateless.

Key Characteristics

  • Uses HTTP/HTTPS for communication
  • Stateless architecture
  • Resource-based URLs
  • Lightweight and easy to understand
  • Usually exchanges data in JSON format
  • Highly scalable

Common HTTP Methods

MethodPurpose
GETRetrieve data
POSTCreate new data
PUTUpdate existing data
PATCHPartially update data
DELETEDelete existing data

Example

HTTP Request

GET /users/123 HTTP/1.1
Host: example.com

Response

{
    "id": 123,
    "name": "John Doe",
    "email": "john@example.com"
}

Advantages

  • Simple to learn
  • Lightweight
  • Fast
  • Cacheable
  • Excellent browser support

Limitations

  • Over-fetching and under-fetching of data
  • Multiple requests may be required
  • No built-in schema

Common Use Cases

  • Web applications
  • Mobile applications
  • Public APIs
  • E-commerce applications
  • Social media platforms

2. SOAP (Simple Object Access Protocol)

SOAP stands for Simple Object Access Protocol.

Unlike REST, SOAP is a strict messaging protocol that primarily uses XML for communication.

SOAP is commonly used in enterprise applications where security, reliability, and transactional integrity are essential.

Key Characteristics

  • XML-based messaging
  • Strict communication standard
  • Built-in error handling
  • Supports WS-Security
  • Platform independent
  • Highly secure

Example

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <GetUserDetails>
            <UserId>123</UserId>
        </GetUserDetails>
    </soap:Body>
</soap:Envelope>

Advantages

  • High security
  • Built-in standards
  • Reliable messaging
  • Supports transactions

Limitations

  • XML messages are larger
  • Slower than REST
  • More complex to implement

Common Use Cases

  • Banking systems
  • Healthcare applications
  • Government services
  • Enterprise software
  • Financial transactions

3. GraphQL

GraphQL is a query language for APIs developed by Facebook (Meta).

Instead of exposing multiple endpoints, GraphQL exposes a single endpoint where clients specify exactly what data they need.

This solves the common REST problem of over-fetching and under-fetching.

Key Characteristics

  • Single API endpoint
  • Client specifies required data
  • JSON responses
  • Strongly typed schema
  • Efficient data fetching

Example

Query

{
    user(id: "123") {
        name
        email
        posts {
            title
            comments {
                text
            }
        }
    }
}

Advantages

  • No over-fetching
  • No under-fetching
  • Flexible queries
  • Reduces network requests

Limitations

  • More difficult caching
  • Complex backend implementation
  • Higher learning curve

Common Use Cases

  • Mobile applications
  • Social media platforms
  • Dashboards
  • Applications with complex relationships

4. gRPC (Google Remote Procedure Call)

gRPC stands for Google Remote Procedure Call.

It is a high-performance Remote Procedure Call (RPC) framework developed by Google.

Instead of JSON or XML, gRPC uses Protocol Buffers (Protobuf) for serialization, making communication extremely fast and compact.

It runs on HTTP/2, which supports multiplexing and bidirectional streaming.

Key Characteristics

  • Uses Protocol Buffers
  • Operates over HTTP/2
  • Extremely fast
  • Small payload size
  • Supports streaming
  • Cross-language support

Example

service UserService {

    rpc GetUserDetails(UserRequest)
        returns (UserResponse);

}

message UserRequest {

    int32 user_id = 1;

}

message UserResponse {

    int32 user_id = 1;
    string name = 2;
    string email = 3;

}

Advantages

  • Very high performance
  • Compact messages
  • Strongly typed
  • Excellent for microservices
  • Supports streaming

Limitations

  • Harder to debug
  • Browser support is limited
  • Requires Protocol Buffer compilation

Common Use Cases

  • Microservices
  • Distributed systems
  • Cloud infrastructure
  • Internal APIs
  • AI/ML serving

5. WebSocket

WebSocket is a communication protocol that enables full-duplex communication between a client and a server over a single TCP connection.

Unlike REST, where every request requires a new HTTP request-response cycle, WebSocket keeps the connection open, allowing both the client and server to exchange data continuously.

This makes it ideal for real-time applications.

Key Characteristics

  • Persistent connection
  • Full-duplex communication
  • Low latency
  • Real-time messaging
  • Efficient for continuous updates

Example

const socket = new WebSocket("ws://example.com/stocks");

socket.onmessage = (event) => {
    console.log("Stock Update:", event.data);
};

Advantages

  • Real-time communication
  • Very low latency
  • Reduces network overhead
  • Bi-directional messaging

Limitations

  • More difficult to scale
  • Connection management required
  • Not ideal for simple CRUD APIs

Common Use Cases

  • Chat applications
  • Live notifications
  • Online gaming
  • Stock market dashboards
  • Collaborative editors
  • Live sports scores

REST vs SOAP vs GraphQL vs gRPC vs WebSocket

FeatureRESTSOAPGraphQLgRPCWebSocket
Communication StyleHTTPXML ProtocolQuery LanguageRPC FrameworkPersistent TCP Connection
Data FormatJSON, XMLXMLJSONProtocol BuffersAny Format
PerformanceFastModerateFastVery FastExtremely Fast
FlexibilityHighLowVery HighMediumHigh
Real-Time SupportNoNoLimitedYesYes
Multiple EndpointsYesYesNoYesNo
SecurityHTTPSWS-SecurityHTTPSTLSTLS
StreamingNoNoLimitedYesYes
Learning CurveEasyModerateModerateAdvancedModerate
Best ForPublic APIsEnterprise SystemsMobile AppsMicroservicesReal-Time Applications

Which API Protocol Should You Choose?

Choose REST if:

  • You’re building a standard web or mobile API.
  • Simplicity and scalability are important.

Choose SOAP if:

  • Security and reliability are critical.
  • You’re working with enterprise or financial systems.

Choose GraphQL if:

  • Clients need flexible access to data.
  • You want to eliminate over-fetching.

Choose gRPC if:

  • Performance is your top priority.
  • You’re building microservices or distributed systems.

Choose WebSocket if:

  • Your application requires real-time communication.
  • Data needs to be pushed instantly to connected clients.

API Components Explained: Endpoint, Request, Response, and Rate Limiting

Whenever a client communicates with an API, several key components work together to process the request and return the desired result. Understanding these components is essential for anyone learning REST APIs, FastAPI, or backend development.

In this guide, we’ll explore the four fundamental API components:

  • Endpoint
  • Request
  • Response
  • Rate Limiting & Quotas

1. Endpoint

An Endpoint is the specific URL where an API can be accessed to perform a particular operation.

You can think of an endpoint as the address of a resource on the server. Each endpoint is associated with a specific functionality, such as retrieving users, creating products, or deleting orders.

For example, an API may expose different endpoints for different resources:

  • /users
  • /products
  • /orders
  • /posts

Each endpoint acts as the communication point between the client and the server.

Key Characteristics

  • Unique URL for accessing a resource
  • Communication touchpoint between client and server
  • Usually contains path parameters and query parameters
  • Supports one or more HTTP methods (GET, POST, PUT, DELETE)

Example

GET https://api.example.com/users/123

Path Parameter

/users/123
       ↑
   User ID

Query Parameters

/products?category=laptop&page=2&sort=price

2. API Request

An API Request is the message sent by a client to the server asking it to perform a specific operation.

Every request contains information that helps the server understand:

  • What operation should be performed?
  • Which resource is required?
  • What data should be processed?

Components of an API Request

1. HTTP Method

Specifies the type of operation.

MethodPurpose
GETRetrieve data
POSTCreate data
PUTReplace existing data
PATCHPartially update data
DELETERemove data

2. Request Headers

Headers contain metadata about the request.

Common request headers include:

HeaderPurpose
Content-TypeFormat of request body
AuthorizationAuthentication token
AcceptExpected response format
User-AgentClient information

3. Request Body

The request body contains the actual data being sent to the server.

It is commonly used with POST, PUT, and PATCH requests.

Example JSON Body

{
    "name": "John Doe",
    "email": "john@example.com"
}

Complete Request Example

POST /users HTTP/1.1
Host: api.example.com

Content-Type: application/json
Authorization: Bearer token123

{
    "name": "John Doe",
    "email": "john@example.com"
}

3. API Response

After processing the request, the server sends an API Response back to the client.

The response informs the client whether the request was successful and may also include the requested data.

Components of an API Response

HTTP Status Codes Overview

HTTP Status Codes indicate whether an API request was processed successfully or encountered an error. They help clients understand the outcome of every request.

📤 API Request 🖥️ API Server Processes Request ✅ 2xx Success 200 OK → Request Successful 201 Created → Resource Created 204 No Content → Success No Response Body ⚠️ 4xx Client Errors 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found ❌ 5xx Server Errors 500 Internal Server Error Unexpected server failure Requires backend investigation
How to Read HTTP Status Codes
  • 2xx → The request was processed successfully.
  • 4xx → The client sent an invalid request or lacks permission.
  • 5xx → The server encountered an unexpected error while processing the request.

2. Response Headers

Headers provide additional information about the response.

Common response headers include:

HeaderPurpose
Content-TypeResponse data format
Content-LengthResponse size
Cache-ControlCaching instructions
ServerServer information

3. Response Body

The response body contains the data returned by the API.

Most modern APIs return JSON.

Example

{
    "id": 123,
    "name": "John Doe",
    "email": "john@example.com"
}

Complete Response Example

HTTP/1.1 200 OK

Content-Type: application/json

{
    "id": 123,
    "name": "John Doe",
    "email": "john@example.com"
}

API Request vs API Response

API RequestAPI Response
Sent by the clientSent by the server
Contains endpointContains status code
Includes HTTP methodIncludes response headers
Includes request headersIncludes response body
May contain request bodyReturns requested data or error

4. Rate Limiting and Quotas

Most public APIs restrict the number of requests a client can make within a certain period.

This mechanism is called Rate Limiting.

A Quota defines the maximum number of requests allowed during a specific time window.

Rate limiting protects servers from abuse, prevents denial-of-service attacks, and ensures fair usage among all users.

Why is Rate Limiting Important?

  • Prevents API abuse
  • Protects server resources
  • Ensures fair usage
  • Improves API reliability
  • Helps control infrastructure costs

Common Rate Limiting Headers

HeaderDescription
X-RateLimit-LimitMaximum requests allowed in the current window
X-RateLimit-RemainingRequests remaining before reaching the limit
X-RateLimit-ResetTime when the rate limit resets
Retry-AfterNumber of seconds to wait before retrying

Example Response Headers

HTTP/1.1 429 Too Many Requests

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
Retry-After: 60

This response indicates that the client has exceeded the allowed request limit and must wait 60 seconds before making another request.


Summary

ComponentPurpose
EndpointSpecifies the URL where the API resource can be accessed.
RequestMessage sent by the client containing the method, headers, and optional body.
ResponseMessage returned by the server containing the status code, headers, and response data.
Rate LimitingRestricts the number of requests to protect the API and ensure fair usage.

API Lifecycle

API Lifecycle Overview

🎯 Planning Design API 💻 Development Build API ☁️ Deployment Release API 📊 Monitoring Optimize 🔄 Versioning Improve API 🏁 Retirement Deprecate API

Phase Key Activities Tools & Technologies Primary Outcome
🎯 Planning & Design • Identify business goals & user needs
• Determine target audience (devs, partners, internal)
• Define endpoints, request/response formats & data models
• Choose methodology: REST, GraphQL, or gRPC
Postman
SwaggerHub
Stoplight
Clear, user‑centric API blueprint
💻 Development • Write server‑side backend logic
• Integrate authentication & security mechanisms
• Perform unit testing (validate individual functions)
• Set up CI/CD pipelines
Git Jenkins
Docker / K8s Flask
FastAPI Express.js
Functional, secure & testable implementation
☁️ Deployment • Deploy to staging, testing & production environments
• Leverage cloud services for scalability & reliability
• Set up API gateway for routing, caching & load balancing
AWS Azure GCP
AWS API Gateway
Kong Apigee
Accessible, scalable & reliable API
📊 Monitoring & Management • Track performance (response times, uptime, error rates)
• Gather usage data (traffic patterns, popular endpoints)
• Identify optimization areas
• Enforce rate limiting to prevent abuse
Datadog New Relic
Grafana
High availability & optimized performance
🔄 Updates & Versioning • Ensure new updates don’t break existing clients
• Provide clear migration paths for breaking changes
• Notify users in advance of deprecated features/versions
• Offer timelines & transition guidelines
Semantic Versioning
API deprecation headers
Smooth evolution without client disruption
🏁 Retirement • Inform stakeholders & users well in advance
• Provide tools/resources to transition to newer APIs
• Archive or securely dispose of associated stored data
Migration tooling
Secure data purging
Graceful phase‑out while maintaining user trust

APIs Quiz

Q.1 What is the primary purpose of an API (Application Programming Interface)?



  • To design graphical user interfaces


  • To enable communication and data exchange between different software applications


  • To store application data permanently


  • To compile programming languages into machine code

Q.2 Which type of API allows applications to communicate over the internet using HTTP or HTTPS?



  • Hardware API


  • Library API


  • Web API


  • GUI API

Q.3 Which of the following is an example of a Library API?



  • Google Maps API


  • AWS EC2 API


  • NumPy API


  • Firebase Authentication API

Q.4 Which statement correctly describes a Remote API?



  • It only works inside the same application.


  • It allows communication with systems located on another network or server.


  • It is used only for graphical user interfaces.


  • It can only access local databases.

Q.5 Which API is specifically designed to perform CRUD operations on databases?



  • Database API


  • Hardware API


  • GUI API


  • Library API

Q.6 Which of the following is an example of a Hardware API?



  • Tkinter


  • CUDA


  • Postman


  • SwaggerHub

Q.7 Which API is primarily used to build graphical user interfaces?



  • Database API


  • Web API


  • GUI API


  • Remote API

Q.8 Which API architecture follows a stateless communication model and commonly uses HTTP methods like GET, POST, PUT, and DELETE?



  • SOAP


  • REST


  • GraphQL


  • gRPC

Q.9 Which stage of the API Lifecycle focuses on tracking response time, uptime, error rates, and API usage?



  • Development


  • Planning and Design


  • Monitoring and Management


  • Retirement

Q.10 What is the primary goal of API Versioning during the API Lifecycle?



  • To permanently delete old APIs immediately


  • To improve hardware performance


  • To introduce changes without breaking existing client applications


  • To reduce the number of API endpoints

Scroll to Top