Search This Blog

Showing posts with label REST API. Show all posts
Showing posts with label REST API. Show all posts

Saturday, November 9, 2024

Boost API Performance with these Strategies

 1. Use Caching


Description: Caching stores frequently accessed data temporarily in memory.
Benefits: Speeds up response times by avoiding repeated database access.
Implementation Tips: Use in-memory solutions like Redis for high-speed data retrieval.

2. Minimize Payload Size

Description: Reduce data in responses to only the essentials.
Benefits: Saves bandwidth and enhances speed, especially in large datasets.
Implementation Tips: Use field filtering, compression, and pagination to control payload size.

3. Asynchronous Processing

Description: Run non-critical processes asynchronously to keep APIs available.
Benefits: Ensures users receive faster responses for essential actions.
Implementation Tips: Use queues or async frameworks for background processing of tasks like logging or notifications.

4. Load Balancing

Description: Distribute incoming API requests among multiple servers.
Benefits: Increases reliability and can handle a larger load.
Implementation Tips: Set up load balancers to dynamically allocate traffic based on server capacity.

5. Optimize Data Formats

Description: Use efficient formats like JSON or Protocol Buffers instead of bulkier options like XML.
Benefits: Smaller formats decrease the time required for data parsing and transmission.
Implementation Tips: Prefer binary formats for internal communication to reduce payload size further.

6. Connection Pooling

Description: Reuse open connections to databases or services rather than reconnecting each time.
Benefits: Reduces latency from establishing connections and speeds up requests.
Implementation Tips: Implement connection pools with configurable limits to handle concurrent requests efficiently.

7. Use Content Delivery Networks (CDNs)

Description: CDNs cache static content closer to the end user.
Benefits: Decreases latency by shortening data travel distances.
Implementation Tips: Use for static assets like images or JavaScript files for APIs needing regular access to such resources.

8. Implement API Gateway

Description: API gateways manage request routing, authentication, rate limiting, and caching.
Benefits: Enhances API scalability and offloads repetitive tasks.
Implementation Tips: Configure API gateways to route requests based on type, manage security, and throttle traffic effectively.

9. Avoid Overfetching and Underfetching

Description: Build endpoints to return exactly what the client needs, neither too much nor too little.
Benefits: Reduces unnecessary data transfer, improving performance and efficiency.
Implementation Tips: Use GraphQL to allow clients to specify precise data needs, addressing common issues in REST APIs.
Using these strategies can significantly improve API responsiveness, enhance user experience, and scale infrastructure effectively.



Saturday, April 30, 2022

Rest API Design - OTP based Auth API

Learn how to design REST API with a real world example. We build an OTP based auth API with /signup, /login, /send-otp and /validate-otp features.

Problem statement:

Design the auth flow apis (signup, login, etc) for an OTP based user authentication. Assume OTP will be created and presented to users upon a successful login.


API Signature:

- URL

- Request Method

- Request Headers

- Request Body

- Response Status code

- Response Headers

- Response Body


Signup API:

  • URL
  • Request method: GET, PUT, POST, DELETE, PATCH, OPTIONS
    • Which method should we use here?
    • POST
    • POST vs PUT? Idempotency
  • Request Headers:
    • Content Type: application/json
    • any others?
  • Request Body: Form Data, XML, JSON, i.e. Content Type
    • JSON body:
  •   {
  •     "email": "foo@bar.com",
  •     "password": "supersecret", // plaintext password, yikes!
  •     "phone": "+91-9876543210"
  •   }

  • Logic on server side?
    • Validate request body
    • Insert record in DB
    • Handle errors
  • Response Status code: 2xx, 3xx, 4xx, 5xx
    • 200 ok or
    • 201 created
  • Response Headers:
    • Content Type if we are sending any content back
    • Any other headers?
  • Response Body:
    • Empty body or
    • Some useful content (user id?)


Login API:

  • URL https://<name>.com/api/v1/login
  • Request method: POST
  • Request Headers:
    • Content Type: application/json
    • any others?
  • Request Body:
    • JSON body:
  •   {
  •     "email": "foo@bar.com",
  •     "password": "supersecret", // plaintext password, yikes!
  •   }

  • Logic on server side?
    • Validate request body
    • Check email and password combination
    • Handle errors
    • Create a token and send token back to user. Why?
  • Response Status code: 2xx, 3xx, 4xx, 5xx
    • 200 ok
    • 4xx client side errors (validation of email, invalid credentials or unauthorized)
    • 5xx server side errors (DB down so not able to login the user)
  • Response Headers:
    • Content Type if we are sending any content back
    • Any other headers?
      • Return a time limited token in headers
      • Why do we need this? Let's come back to it when we talk about validate OTP API
  • Response Body:
    • Empty body or
    • Send OTP as part of response?
    • When do we actually send the OTP to user? Is it a UI triggered action? Or a "side-effect" of successful login


Send OTP API:

  • URL https://<name>.com/api/v1/send-otp
  • Request method: POST
  • Request Headers:
    • Token received from Login API reponse. Why?
    • any others?
  • Request Body:
    • Empty body or
    • Should we send phone number to send OTP to?
  • Logic on server side?
    • Validate token from headers
    • Figure out phone number from token
    • Sent OTP, store OTP in some storage for validation
  • Response Status code: 2xx, 3xx, 4xx, 5xx
    • 200 ok
    • 4xx client side errors (invalid token, i.e. unauthorized)
    • 5xx server side errors (Third party SMS vendor down, DB down, etc. so not able to send OTP the user)
  • Response Headers:
    • None that I can think of
  • Response Body:
    • Empty body


Validate OTP API:

  • URL https://<name>.com/api/v1/validate-otp
  • Request method: POST, or GET. Any query params?
  • Request Headers:
    • Token received from Login API reponse. Why?
    • any others?
  • Request Body:
    • JSON body
  • {
  •     "otp": "123456"
  • }

  • Logic on server side?
    • Validate token
    • Check token and OTP combination are correct
    • Handle errors
  • Response Status code: 2xx, 3xx, 4xx, 5xx
    • 200 ok
    • 4xx client side errors (invalid token, i.e. unauthorized, invalid otp, expired otp, etc.)
    • 5xx server side errors (DB down so not able to validate OTP)
  • Response Headers:
    • None that I can think of
  • Response Body:
    • Empty body


Do you see any challenges/unknowns?

  • Token before and after OTP validation is same. Is it okay? What problems can it cause?
  • What if user requests for OTP multiple times? (both legit and abuser use case)
  • Where do we store OTPs, Tokens?
  • Can this API be used by both web and mobile?

My Profile

My photo
can be reached at 09916017317