π Introduction to REST APIs
REST API stands for Representational State Transfer Application Programming Interface. Don't worry about the fancy name - it's simply a way for different software applications to communicate with each other over the internet.
Think of a REST API like a waiter in a restaurant:
- You (the client) - like a customer who wants to order food
- The API (the waiter) - takes your order and brings back your food
- The kitchen (the server) - prepares your order and sends it back
π‘ Simple Definition: A REST API is a set of rules that allow apps to request and exchange data over the internet using simple HTTP requests.
REST APIs are everywhere! When you:
- Check the weather on your phone app
- Post a photo on social media
- Order food through a delivery app
- Send a message in a chat app
Your app is likely talking to a REST API to get or send that information.
π§ HTTP Methods (The API Verbs)
REST APIs use different HTTP methods (also called "verbs") to perform different actions. Think of these as commands you give to the API:
Retrieve Data
Used to fetch or read information from the server. Like asking "Show me all users" or "Get user with ID 5".
Example: Getting a list of blog posts
Create New Data
Used to create or add new information to the server. Like submitting a form or creating a new user account.
Example: Creating a new blog post
Update Existing Data
Used to update or modify existing information. Like editing your profile or updating a blog post.
Example: Updating user profile information
Remove Data
Used to delete or remove information from the server. Like deleting a post or removing a user account.
Example: Deleting a blog post
π― Remember CRUD: Create (POST), Read (GET), Update (PUT), Delete (DELETE) - these four operations cover most of what you'll do with APIs!
π» Practical Examples with Our Fake API
Let's see these HTTP methods in action using our fake REST API. These examples work right now - you can copy and test them!
π GET: Reading Data
The most common operation - getting data from the API:
// Get all users const users = await fetch('https://fake-rest-api-mobile-apps.vercel.app/api/users') .then(response => response.json()); console.log(users); // Array of user objects // Get specific user by ID const user = await fetch('https://fake-rest-api-mobile-apps.vercel.app/api/users/1') .then(response => response.json()); console.log(user); // Single user object
βοΈ POST: Creating New Data
Adding new information to the API:
// Create a new user const newUser = await fetch('https://fake-rest-api-mobile-apps.vercel.app/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John Doe', email: 'john@example.com', phone: '+1-555-123-4567' }) }).then(response => response.json()); console.log(newUser); // The created user with new ID
π PUT: Updating Data
Modifying existing information:
// Update user with ID 1 const updatedUser = await fetch('https://fake-rest-api-mobile-apps.vercel.app/api/users/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Jane Smith', email: 'jane@example.com', phone: '+1-555-987-6543' }) }).then(response => response.json()); console.log(updatedUser); // The updated user data
ποΈ DELETE: Removing Data
Deleting information from the API:
// Delete user with ID 1 const response = await fetch('https://fake-rest-api-mobile-apps.vercel.app/api/users/1', { method: 'DELETE' }); if (response.status === 204) { console.log('User deleted successfully!'); }
π HTTP Status Codes
When you make a request to an API, it responds with a status code that tells you what happened. Think of these like emoji reactions to your request:
Status Code | Meaning | Description |
---|---|---|
200 | OK | β Success! Your request worked perfectly |
201 | Created | β Success! Something new was created (POST requests) |
204 | No Content | β Success! Action completed, no data to return (DELETE) |
400 | Bad Request | β Your request was malformed or missing required data |
404 | Not Found | β The endpoint or resource you requested doesn't exist |
429 | Too Many Requests | βΈοΈ You're making requests too fast (rate limiting) |
500 | Internal Server Error | π₯ Something went wrong on the server (not your fault!) |
π― Quick Reference: 2xx = Success, 3xx = Redirect, 4xx = Client Error (your fault), 5xx = Server Error (not your fault)
π JSON: The Language of APIs
REST APIs typically send and receive data in JSON format (JavaScript Object Notation). JSON is like a universal language that all programming languages can understand.
JSON looks like this:
{ "id": 1, "name": "John Doe", "email": "john@example.com", "isActive": true, "age": 30, "hobbies": ["reading", "coding", "gaming"], "address": { "street": "123 Main St", "city": "New York", "zipcode": "10001" } }
JSON Rules:
- Strings must be in double quotes:
"hello"
- Numbers can be integers or decimals:
42
,3.14
- Booleans are true or false:
true
,false
- Arrays use square brackets:
[1, 2, 3]
- Objects use curly braces:
{"key": "value"}
β οΈ Common JSON Mistakes: Using single quotes instead of double quotes, forgetting commas between items, or having trailing commas.
π― Understanding API Endpoints
An endpoint is like a specific address where you can find certain data. Each endpoint has a URL and accepts specific HTTP methods.
Endpoint Structure:
https://fake-rest-api-mobile-apps.vercel.app/api/users/123 βββββββββββββββββββ ββββββββ βββββββ βββ Base URL Path Resource ID
Common Endpoint Patterns:
/api/users
- Get all users or create a new user/api/users/123
- Get, update, or delete user with ID 123/api/users/123/posts
- Get all posts by user 123/api/posts?category=tech
- Get posts filtered by category
ποΈ RESTful Pattern: Collection endpoints (plural nouns) for multiple items, individual endpoints for single items.
π Query Parameters
Query parameters let you filter, sort, and customize your API requests. They're added to the URL after a ?
symbol.
Common Query Parameters:
// Pagination /api/users?_page=2&_limit=10 // Filtering /api/posts?userId=5&category=technology // Searching /api/users?q=john // Sorting /api/products?_sort=price&_order=asc // Combining multiple parameters /api/todos?userId=1&completed=false&_page=1&_limit=5
Try These with Our API:
// Get completed todos for user 50 const completedTodos = await fetch( 'https://fake-rest-api-mobile-apps.vercel.app/api/todos?userId=50&completed=true' ).then(res => res.json()); // Get first 5 products const products = await fetch( 'https://fake-rest-api-mobile-apps.vercel.app/api/products?_page=1&_limit=5' ).then(res => res.json());
β API Best Practices for Mobile Developers
1. Handle Errors Gracefully
async function fetchUserSafely(userId) { try { const response = await fetch(`/api/users/${userId}`); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const user = await response.json(); return user; } catch (error) { console.error('Failed to fetch user:', error.message); // Show user-friendly error message return null; } }
2. Use Loading States
const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetchUsers() .then(data => { setUsers(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []);
3. Respect Rate Limits
- Don't make too many requests too quickly
- Check rate limit headers in responses
- Implement retry logic with exponential backoff
- Cache responses when possible
4. Validate Data
- Always validate data before sending to API
- Check required fields are present
- Validate data types and formats
- Show clear validation error messages
π§ͺ How to Test APIs
There are several ways to test REST APIs. Here are the most popular tools:
1. Browser Developer Tools
Press F12 in your browser and use the Network tab to see API requests in real-time.
2. Postman
A popular desktop app for testing APIs with a user-friendly interface.
3. curl (Command Line)
# GET request curl https://fake-rest-api-mobile-apps.vercel.app/api/users # POST request curl -X POST \ -H "Content-Type: application/json" \ -d '{"name":"John","email":"john@example.com"}' \ https://fake-rest-api-mobile-apps.vercel.app/api/users
4. Our Interactive Tester
We have a built-in API tester on our main page! You can test all endpoints without writing any code.
π Next Steps
Now that you understand REST APIs, here's what you can do next:
- Practice with our API: Use our interactive tester to try different endpoints
- Build a simple app: Create a mobile app that displays data from our API
- Learn about authentication: Most real APIs require API keys or OAuth
- Explore advanced topics: Pagination, webhooks, rate limiting
- Read API documentation: Practice reading real API docs from services you use
π‘ Pro Tip: Start small! Build a simple app that just displays a list of users or posts. Once that works, add features like creating, editing, and deleting data.
Ready to start building?
Head back to our API documentation and start experimenting!
Start Building with Our API