0% found this document useful (0 votes)
24 views28 pages

Week 8

The document provides an overview of API integrations, explaining what APIs are, how they work, and their importance in software applications. It covers REST architecture, JSON data handling in Flutter, error handling, and the use of the Dio library for HTTP requests. Additionally, it discusses best practices for API implementation and the use of enums in Flutter for state management.

Uploaded by

Steve Tyga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views28 pages

Week 8

The document provides an overview of API integrations, explaining what APIs are, how they work, and their importance in software applications. It covers REST architecture, JSON data handling in Flutter, error handling, and the use of the Dio library for HTTP requests. Additionally, it discusses best practices for API implementation and the use of enums in Flutter for state management.

Uploaded by

Steve Tyga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

WEEK 8

UNDERSTANDING API INTEGRATIONS

GovindDev | Flutter Dev | Kan Myint Htun


What is an API?
API (Application Programming Interface):

A way for two software applications to communicate with each other.

APIs allow apps to send and receive data from external services.



UNDERSTANDING
Simple Analogy

Imagine a restaurant:

API
 The customer (your app) wants food (data).

INTEGRATIONS The chef (the server) prepares it.

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.

2. API Server processes the request and retrieves the data.

3. Response is sent back to the client.



Why are APIs Important?

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:

Modern apps rely on APIs to connect with databases, third-party


services, and other systems.

Interoperability:

Connect apps written in different programming languages.


GovindDev | Flutter Dev | Kan Myint Htun
What is REST?
REST (Representational State Transfer):

A style of architecture for designing APIs. REST APIs are stateless and

commonly use HTTP methods.

Common HTTP Methods in REST API

GET: Retrieve data from the server.

REST API
Example: Fetching a list of products (data). (READ)

POST: Send data to the server.

Example: Submitting a new user registration. (CREATE/ADD)

PUT: Update existing data on the server.

Example: Changing user details. (UPDATE)

DELETE: Remove data from the server.

Example: Deleting a post. (DELETE)

GovindDev | Flutter Dev | Kan Myint Htun


JSON (JavaScript Object Notation)
A lightweight format for data exchange between a client and server.

Human-readable and easy to parse in Dart.



Data is organized in key-value pairs.

Example JSON

JSON "id": 1,

"name": "John Doe",

"email": "[email protected]",

"isPremiumUser": true,

}


How to Work with JSON in Flutter

Convert JSON strings to Dart objects using jsonDecode.

Convert Dart objects to JSON strings using jsonEncode.

GovindDev | Flutter Dev | Kan Myint Htun


JSON (JavaScript Object Notation)
Nested JSON DATA Example:

Data is organized in key-value pairs.

"id": 1,

"name": "John Doe",

"address": {

JSON "street": "123 Main St",

"city": "New York"

//jsonData

{},

{},

...

} GovindDev | Flutter Dev | Kan Myint Htun


JSON

GovindDev | Flutter Dev | Kan Myint Htun


JSON

GovindDev | Flutter Dev | Kan Myint Htun


Converting json data to dart code
String jsonString = '''

"id": 1,

"name": "John Doe",

"address": {

"street": "123 Main St",

JSON }

"city": "New York"

''';

void main() {

Map<String, dynamic> user = jsonDecode(jsonString);

print(user['name']); // Output: John Doe

print(user['address']['city']); // Output: New York

GovindDev | Flutter Dev | Kan Myint Htun


WHAT IS MAP?
A Map in Dart is a key-value pair collection, meaning it associates
keys with values. Keys must be unique, and they can map to any type
of value.

Map<KeyType, ValueType> myMap = {};// ‘key’: ‘value’



Example of Map<String, dynamic>

MAP The type Map<String, dynamic> is commonly used in Flutter because it


can store
A string as a key
Any data type (dynamic) as a value.

Map userData = {

'id': '123',

'name': 'John Doe',

'age': 25,

'isPremiumUser': true,

};

GovindDev | Flutter Dev | Kan Myint Htun


Necessary Concepts for API
Implementation
Endpoint

A specific URL where the client (your app) can access a resource.

Example: API Base URL: https://jsonplaceholder.org

UNDERSTANDING
Query Parameters

Additional information sent with a request.

API
 Example: Fetching posts by user ID:

INTEGRATIONS https://jsonplaceholder.org/posts?userId=1

https://jsonplaceholder.org/users?id=1

Request Header

Metadata sent with requests, such as authentication tokens or content


type. Example:

"Authorization": "Bearer <your_token>",

"Content-Type": "application/json"

}
GovindDev | Flutter Dev | Kan Myint Htun
Necessary Concepts for API
Implementation - CONT
Request Body

Data sent to the server with POST, PUT, or DELETE requests.

Example (JSON Body):

UNDERSTANDING
{

"title": "Learning APIs",

API
 "body": "This is a beginner tutorial",

INTEGRATIONS }


"userId": 1

Note : Response body will be dynamic in the Flutter project.

success data error data

GovindDev | Flutter Dev | Kan Myint Htun


Status Codes
When working with APIs, the server responds with status codes to
indicate the result of your request. Understanding these is crucial for
handling API responses.
Status Code Category Meaning
UNDERSTANDING

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

GovindDev | Flutter Dev | Kan Myint Htun


HTTP Status Codes
Categories

2xx: Succes
200: O
UNDERSTANDING
201: Created


API
 4xx: Client Error


INTEGRATIONS 400: Bad Request (e.g., missing fields)
401: Unauthorized (e.g., invalid token)
404: Not Found (e.g., invalid endpoint).


5xx: Server Error if (response.statusCode == 200) {

print('Success');

500: Internal Server Error } else if (response.statusCode == 404) {

503: Service Unavailable. print(‘Page not found');

} else {

print('Error: ${response.statusCode}');

GovindDev | Flutter Dev | Kan Myint Htun


Best Practices When Working with APIs
Always Handle Errors:

Check statusCode to determine if the request was successful.

Use try-catch for network timeouts or connection issues.

UNDERSTANDING
Use Constants for Endpoints:

Define API URLs and endpoints as constants for reusability.

API

INTEGRATIONS Modularize API Calls:

Create a separate api_service.dart file to manage all API-related


logic.

Secure Sensitive Data:

Avoid hardcoding API keys or tokens in the code. Use environment


variables or secure storage.

GovindDev | Flutter Dev | Kan Myint Htun


Understanding enum in Flutter
An enum (short for "enumeration") is a special data type in Dart that
lets you define a set of named constant values.

It's great for representing options, states, or categories in your Flutter


app.

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

enum ApiStatus { initial, loading, success, error }

GovindDev | Flutter Dev | Kan Myint Htun


Understanding enum in Flutter
class RespObj {

dynamic data;

ApiStatus status;

RespObj(this.data, this.status);

ENUM
 // Example usage

void main() {

CLASS RespObj respObj = RespObj('Learn Flutter', ApiStatus.initial);

// Check status

if (respObj.status == ApiStatus.initial) {

print(Response is not started yet.');

// Update status

respObj.status = ApiStatus.success;

print(“Loaded Successfully.');

} GovindDev | Flutter Dev | Kan Myint Htun


Why Use Enums in Flutter?
State Management

Enums can define states in apps like LoadingState { idle, loading,


success, error }.

Dropdown Menus

Enums are perfect for options in drop-downs or selections.

ENUM
 Navigation Logic

CLASS Manage different views or routes with enums.

Theming or Configurations

Define modes like AppTheme { light, dark }.

GovindDev | Flutter Dev | Kan Myint Htun


Why Use Enums in Flutter?
//enum

enum UserRole { admin, user, guest }

void checkAccess(UserRole role) {

switch (role) {

case UserRole.admin:

ENUM
 print('Admin access granted.');

break;

CLASS case UserRole.user:

print('User access granted.');

break;

case UserRole.guest:

print('Guest access limited.');

break;

GovindDev | Flutter Dev | Kan Myint Htun


ERROR HANDLING
try-catch for Error Handling


Purpose: To catch exceptions during API calls and prevent the app
from crashing.

Why Needed

ENUM
 Network issues (e.g., no internet connection)


API issues (e.g., invalid URL, rate limits)
CLASS Server errors (e.g., internal server issues).

How It Helps
Displays meaningful error messages to users
Handles specific errors (e.g., 404, 500) differently.

GovindDev | Flutter Dev | Kan Myint Htun


WHAT IS DIO?
Dio is a third-party library for making HTTP requests in Flutter. It is more
advanced than the http package and provides additional features
like
Interceptors: Modify requests or responses globally
Retry mechanism: Automatically retry failed requests
DIO
 Timeouts: Set time limits for requests
File Upload/Download: Handle files efficiently.

PACKAGE Why Use Dio Over http


Dio is feature-rich and supports more complex use cases
Cleaner syntax for handling requests and responses
Built-in error handling and advanced customization.

dependencies:

dio: ^5.0.0

GovindDev | Flutter Dev | Kan Myint Htun


USING DIO
const baseUrl = 'https://jsonplaceholder.com/posts';


void fetchData() async {

Dio dio = Dio();

try {

DIO
 final response = await dio.get(baseUrl);

// Prints the response JSON

PACKAGE }

print(response.data);

on DioException catch (e) {

/*

if(){}

else{}

*/

throw Exception(e.error.toString());

GovindDev | Flutter Dev | Kan Myint Htun


Features of Dio
1. Customizing Base URL

Set a base URL for your API calls using BaseOptions:


Dio dio = Dio(BaseOptions(

baseUrl: baseUrl

DIO
 ));



PACKAGE void fetchPosts() async {

final response = await dio.get('/posts');

// Automatically appends "/posts" to baseUrl

print(response.data);

GovindDev | Flutter Dev | Kan Myint Htun


Features of Dio - Cont
2. Query Parameters

Add query parameters to a request


void fetchWithQuery() async {

final response = await dio.get(baseURL, queryParameters: {

DIO
 'userId': 1,

});

PACKAGE // Fetch posts by userId=1

print(response.data);

queryParameter is basically the specific information that we want to


showcase in the application.

For example : getting a response for a specific user with userId


assigned to 1.

GovindDev | Flutter Dev | Kan Myint Htun


NEWS APP
enum

enum ApiState { initial, loading, success, error }

api_response Class

IMPLEMENTING
 class RespObj {

ApiState apiState;

NEWS APP
 dynamic data;

WITH
}


RespObj(this.apiState, this.data);

DIO PACKAGE constants.dart

const baseUrl = "https://newsapi.org/v2";

const apiKey = "0f755dabcd514d15bfe9721c0aeb3444";

GovindDev | Flutter Dev | Kan Myint Htun


NEWS APP
api_service.dart

class APIService {

final Dio dio = Dio();

List lists =[];

IMPLEMENTING
 Future<RespObj> getData() async {

RespObj respObj;

NEWS APP
 try {

WITH
final response = await dio.get(baseUrl,

queryParameters: {

DIO PACKAGE "user": 1,

},

);

if (response.statusCode == 200) {

respObj = RespObj(ApiState.success, response.data);

} else {

respObj = RespObj(ApiState.error, "Something went wrong");

return respObj;

} GovindDev | Flutter Dev | Kan Myint Htun


NEWS APP
api_service.dart - cont.

on DioException catch (e) {

RespObj respObj;

if (e.response != null) {

IMPLEMENTING
 final statusCode = e.response!.statusCode;

if (statusCode == 404) {

NEWS APP
 respObj = RespObj(ApiState.error, "Not found");

WITH
} else if (statusCode == 500) {

respObj = RespObj(ApiState.error, "Server error");

DIO PACKAGE } else {

respObj = RespObj(ApiState.error, "Unknown error");

return respObj;

throw Exception(e.error.toString());

}
GovindDev | Flutter Dev | Kan Myint Htun
Practical json data
[

{"id": 1, "name": "Alice"},

{"id": 2, "name": "Bob"},

]

String jsonString = '''

JSON [

{"id": 1, "name": "Alice"}, //UserModel

{"id": 2, "name": "Bob"}, //UserModel

''';

void main() {

List<dynamic> users = jsonDecode(jsonString);

for (var user in users) {

print(user['name']);

} GovindDev | Flutter Dev | Kan Myint Htun

You might also like