Lesson 124 of 158 – User Interface API
78%

User Interface API

A User Interface API is an API endpoint that returns information about the currently authenticated user. In a React Native application, this information can be used to display the user's name, email, role, profile information, and other account details.

Note: In this lesson, we will learn how to create TypeScript interfaces for user data returned by a PHP REST API and use those types with Axios in React Native.

1. What is a User API?

A User API provides information about a user through an HTTP endpoint.

For example:

GET /api/profile.php

The server can identify the logged-in user using the authentication token and return the user's profile.

2. User API Flow

React Native
      ↓
Authorization Header
      ↓
PHP User API
      ↓
Verify JWT
      ↓
Find User
      ↓
Return JSON
      ↓
React Native

3. Example User Response

{
    "success": true,
    "message": "User profile",
    "user": {
        "id": 101,
        "name": "Rahul Kumar",
        "email": "rahul@example.com",
        "role": "student"
    }
}

4. Creating a User Interface

TypeScript can describe the structure of the user returned by the API.

interface User {
    id: number;
    name: string;
    email: string;
}

5. Adding User Role

interface User {
    id: number;
    name: string;
    email: string;
    role: string;
}

The role can identify whether the user is an admin, teacher, or student.

6. Using Literal Role Types

TypeScript can restrict the role to specific values.

interface User {
    id: number;
    name: string;
    email: string;
    role: "admin" | "teacher" | "student";
}

7. User Profile Response Interface

interface UserProfileResponse {
    success: boolean;
    message: string;
    user: User;
}

This interface describes the complete API response.

8. Axios GET Request

const response =
    await axios.get<UserProfileResponse>(
        "/profile"
    );

console.log(response.data.user.name);

The Axios generic tells TypeScript the expected response type.

9. Sending the JWT Token

const response =
    await axios.get<UserProfileResponse>(
        "/profile",
        {
            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

The token allows the server to identify the authenticated user.

10. User Profile Properties

A user profile may contain properties such as:

  • ID
  • Name
  • Email
  • Mobile number
  • Role
  • Profile image
  • Created date
interface User {
    id: number;
    name: string;
    email: string;
    mobile: string;
    role: string;
}

11. Optional User Properties

Some properties may not be available for every user.

interface User {
    id: number;
    name: string;
    email: string;
    mobile?: string;
    profileImage?: string;
}

The ? means the property is optional.

12. Profile Image Property

interface User {
    id: number;
    name: string;
    email: string;
    profileImage?: string;
}

React Native can use the profile image URL returned by the API.

<Image
    source={{ uri: user.profileImage }}
/>

13. User API with Axios Instance

const api = axios.create({
    baseURL: "https://example.com/api"
});

const response =
    await api.get<UserProfileResponse>(
        "/profile"
    );

An Axios instance keeps API configuration in one place.

14. User API Function

const getUserProfile =
    async (): Promise<UserProfileResponse> => {

    const response =
        await api.get<UserProfileResponse>(
            "/profile"
        );

    return response.data;
};

15. Displaying User Name

const [user, setUser] =
    useState<User | null>(null);

const loadProfile = async () => {

    const result =
        await getUserProfile();

    setUser(result.user);
};

The user state can initially be null until the API response arrives.

16. Using User State in JSX

{user && (
    <View>
        <Text>{user.name}</Text>
        <Text>{user.email}</Text>
        <Text>{user.role}</Text>
    </View>
)}

17. Loading User Data

const [loading, setLoading] =
    useState(false);

const loadProfile = async () => {

    try {

        setLoading(true);

        const result =
            await getUserProfile();

        setUser(result.user);

    } finally {

        setLoading(false);

    }
};

18. User API Error Interface

interface UserApiError {
    success: false;
    message: string;
    code?: string;
}

This can describe a structured error returned by the API.

19. Handling 401 Error

If the JWT is missing, invalid, or expired, the API may return HTTP status 401.

if (error.response?.status === 401) {
    console.log("Please login again");
}

The application can then clear authentication state and navigate to the login screen.

20. User API and Authorization

Authentication identifies the user, while authorization determines whether the user can access a particular resource.

Authorization: Bearer JWT_TOKEN

The PHP API should verify the token and enforce any required permissions.

21. User API Response with Data

Some APIs use a standard data property.

{
    "success": true,
    "message": "Profile loaded",
    "data": {
        "id": 101,
        "name": "Rahul",
        "email": "rahul@example.com",
        "role": "student"
    }
}

22. Interface for Data-Based Response

interface UserResponse {
    success: boolean;
    message: string;
    data: User;
}

Then Axios can use:

const response =
    await api.get<UserResponse>(
        "/profile"
    );

23. User Profile with Additional Information

interface User {
    id: number;
    name: string;
    email: string;
    mobile: string;
    role: "admin" | "teacher" | "student";
    profileImage?: string;
    createdAt: string;
}

The interface should match the actual JSON structure returned by the API.

24. Generic User API Response

interface ApiResponse<T> {
    success: boolean;
    message: string;
    data: T;
}

type UserResponse =
    ApiResponse<User>;

This generic structure can also be reused for other API resources.

25. User API Service

export const getUser =
    async (): Promise<UserResponse> => {

    const response =
        await api.get<UserResponse>(
            "/profile"
        );

    return response.data;
};

Keeping API functions in a service file makes React Native components cleaner.

26. Loading User Profile in useEffect

useEffect(() => {

    const loadProfile = async () => {

        try {

            const result =
                await getUser();

            setUser(result.data);

        } catch (error) {

            console.log(
                "Unable to load profile"
            );

        }
    };

    loadProfile();

}, []);

27. Complete User Interface

interface User {
    id: number;
    name: string;
    email: string;
    mobile?: string;
    role: "admin" | "teacher" | "student";
    profileImage?: string;
    createdAt?: string;
}

interface UserResponse {
    success: boolean;
    message: string;
    data: User;
}

28. Complete Typed User API

import axios from "axios";

interface User {
    id: number;
    name: string;
    email: string;
    role: "admin" | "teacher" | "student";
}

interface UserResponse {
    success: boolean;
    message: string;
    data: User;
}

const api = axios.create({
    baseURL: "https://example.com/api"
});

const getUser =
    async (
        token: string
    ): Promise<UserResponse> => {

    const response =
        await api.get<UserResponse>(
            "/profile",
            {
                headers: {
                    Authorization:
                        `Bearer ${token}`
                }
            }
        );

    return response.data;
};

29. Complete React Native Profile Example

const [user, setUser] =
    useState<User | null>(null);

const loadProfile = async () => {

    try {

        const result =
            await getUser(token);

        if (result.success) {
            setUser(result.data);
        }

    } catch (error) {

        console.log(
            "Profile loading failed"
        );

    }
};

useEffect(() => {
    loadProfile();
}, []);

return (
    <View>

        {user && (
            <>
                <Text>
                    Name: {user.name}
                </Text>

                <Text>
                    Email: {user.email}
                </Text>

                <Text>
                    Role: {user.role}
                </Text>
            </>
        )}

    </View>
);

30. Complete User API Flow

Login
  ↓
Receive JWT
  ↓
Store Authentication State
  ↓
GET /profile
  ↓
Authorization: Bearer JWT
  ↓
PHP Verifies JWT
  ↓
Find User
  ↓
Return UserResponse
  ↓
TypeScript Validates Structure
  ↓
Update React Native State
  ↓
Display User Profile

TypeScript interfaces make user API communication predictable and easier to maintain. The same User interface can be reused in profile screens, authentication state, navigation, and other protected screens.

📌 Key Points

  • A User API returns information about an authenticated user.
  • TypeScript interfaces describe the structure of user data.
  • Axios generics can type API responses.
  • The Authorization header can contain a Bearer JWT.
  • User state can use User | null.
  • Roles can be represented using TypeScript literal types.
  • Optional properties can represent data that may not always exist.
  • HTTP 401 can indicate an invalid or missing authentication token.
  • Generic API responses can make interfaces reusable.
  • The PHP server must enforce authentication and authorization.

🧠 Quick Quiz

Question: Which TypeScript type is suitable when the user may not have been loaded yet?