Week 8
Week 8
APIs allow apps to send and receive data from external services.
UNDERSTANDING
Simple Analogy
Imagine a restaurant:
The waiter (the API) takes the customer’s order and delivers the food.
waiter(api)
C response
response Client-Server Architecture
request
A B
(client)customer chef(server)
GovindDev | Flutter Dev | Kan Myint Htun
How APIs Work?
1. Client (Your App) sends a request to the server via an API.
UNDERSTANDING
Dynamic Data:
Fetch live data like weather updates, stock prices, or news articles.
API
INTEGRATIONS Reusability:
Apps like payment gateways (e.g., Stripe, PayPal, KBZPay) use APIs
across multiple platforms.
Industry Standards:
Interoperability:
A style of architecture for designing APIs. REST APIs are stateless and
REST API
Example: Fetching a list of products (data). (READ)
Example JSON
JSON "id": 1,
"email": "[email protected]",
"isPremiumUser": true,
}
How to Work with JSON in Flutter
"id": 1,
"address": {
//jsonData
{},
{},
...
"id": 1,
"address": {
JSON }
''';
void main() {
Map userData = {
'id': '123',
'age': 25,
'isPremiumUser': true,
};
A specific URL where the client (your app) can access a resource.
UNDERSTANDING
Query Parameters
INTEGRATIONS https://jsonplaceholder.org/posts?userId=1
https://jsonplaceholder.org/users?id=1
Request Header
"Content-Type": "application/json"
}
GovindDev | Flutter Dev | Kan Myint Htun
Necessary Concepts for API
Implementation - CONT
Request Body
UNDERSTANDING
{
INTEGRATIONS }
"userId": 1
API
200/201 Success Request was successful, and the response
contains the expected data.
INTEGRATIONS 400 Bad Request The request was invalid (e.g., missing required
fields).
401 Unauthorized Authentication is required or failed.
403 Forbidden You do not have permission to access the
resource.
404 Not Found The requested resource was not found.
500 Internal Server Error The server encountered an error
2xx: Succes
200: O
UNDERSTANDING
201: Created
print('Success');
} else {
print('Error: ${response.statusCode}');
UNDERSTANDING
Use Constants for Endpoints:
API
INTEGRATIONS Modularize API Calls:
In this week , enum is used for defining states for api responses,
making your code cleaner, easier to read, and handle error.
ENUM
CLASS Key Features of enum
Named Constants: Instead of using plain strings or integers, you
can use meaningful names for constants
Type Safety: Enums are type-safe, meaning you can't assign invalid
values
Cleaner Code: Enums make code easier to understand and
maintain.
//example
dynamic data;
ApiStatus status;
RespObj(this.data, this.status);
void main() {
// Check status
if (respObj.status == ApiStatus.initial) {
// Update status
respObj.status = ApiStatus.success;
print(“Loaded Successfully.');
Dropdown Menus
Theming or Configurations
switch (role) {
case UserRole.admin:
break;
break;
case UserRole.guest:
break;
Purpose: To catch exceptions during API calls and prevent the app
from crashing.
Why Needed
How It Helps
Displays meaningful error messages to users
Handles specific errors (e.g., 404, 500) differently.
dependencies:
dio: ^5.0.0
try {
PACKAGE }
print(response.data);
/*
if(){}
else{}
*/
throw Exception(e.error.toString());
baseUrl: baseUrl
DIO ));
print(response.data);
DIO 'userId': 1,
});
print(response.data);
api_response Class
ApiState apiState;
WITH
}
RespObj(this.apiState, this.data);
class APIService {
RespObj respObj;
WITH
final response = await dio.get(baseUrl,
queryParameters: {
},
);
if (response.statusCode == 200) {
} else {
return respObj;
RespObj respObj;
if (e.response != null) {
if (statusCode == 404) {
WITH
} else if (statusCode == 500) {
return respObj;
throw Exception(e.error.toString());
}
GovindDev | Flutter Dev | Kan Myint Htun
Practical json data
[
]
String jsonString = '''
JSON [
''';
void main() {
print(user['name']);