BackendAPI

REST API Tutorial - Build & Test APIs Like a Pro

TT
TopicTrick
REST API Tutorial - Build & Test APIs Like a Pro

REST API Tutorial - Build & Test APIs Like a Pro

REST (Representational State Transfer) APIs are the backbone of modern web applications. Every time you fetch a weather forecast, load tweets, or process a payment, you're almost certainly consuming a REST API.

Understanding how to build, design, and test REST APIs is one of the most valuable skills a developer can have.


What is a REST API?

Think of a REST API as a standard way for your phone or browser to "talk" to a server. Before REST, every system had its own unique way of speaking. REST introduced a set of rules that made it so every computer could understand the same basic commands, like "give me this data" or "save this new user."

A true REST API follows these core principles:

  1. Client-Server: Separation of the user interface (client) from data storage (server).
  2. Stateless: Each request contains all the necessary information; the server doesn't remember previous requests.
  3. Cacheable: Responses should indicate if they can be cached to save bandwidth.
  4. Uniform Interface: Consistent resource naming (URLs) and HTTP methods.

Real-World Analogy

A REST API is like a restaurant menu. You (the client) choose items by name (the URL), tell the waiter what to do (the HTTP method), and the kitchen (the server) fulfills your request without knowing or caring who you are between requests.


    HTTP Methods & Status Codes

    When you use a REST API, you're usually doing one of four things: creating, reading, updating, or deleting data. We use specific "verbs" called HTTP methods to tell the server exactly which action we want to perform.

    Standard HTTP Methods (Verbs)

    MethodPurposeIs it Idempotent?
    GETRetrieve data (Read)Yes
    POSTCreate a new resourceNo
    PUTReplace a resource entirelyYes
    PATCHPartially update a resourceNo
    DELETERemove a resourceYes

    (Note: "Idempotent" means making the same request multiple times will have the same result as making it once. Deleting a user multiple times still just results in a deleted user).

    Common HTTP Status Codes

    The server uses Status Codes to tell us if our request worked or if something went wrong:

    • 200 OK: Standard response for successful GET, PUT, or PATCH requests.
    • 201 Created: A new resource has been successfully created (POST).
    • 400 Bad Request: The server cannot process the request due to client-side errors.
    • 401 Unauthorized: Authentication is required and failed.
    • 404 Not Found: The requested resource could not be found.
    • 500 Server Error: The server crashed or encountered an unexpected bug.

    REST API Design Principles

    Building an API is easy; building an API that other developers actually want to use is hard. Good design means your API is predictable.

    URL Structure Best Practices

    Always use resource-based, lowercase nouns in the plural form. Do not use verbs in the URL.

    text
    1# ✅ Good - resource-based, lowercase, plurals, hyphens 2GET /api/v1/blog-posts 3GET /api/v1/users/123/enrolled-courses 4 5# ❌ Bad - verb-based, inconsistent, camelCase in URLs 6GET /api/getUser 7POST /api/createNewBlogPost

    Consistent JSON Responses

    Always return a consistent JSON structure so clients know exactly what to expect.

    json
    1// Success response 2{ 3 "success": true, 4 "data": { 5 "id": 123, 6 "name": "Alex Chen", 7 "email": "alex@example.com" 8 } 9} 10 11// Error response 12{ 13 "success": false, 14 "error": { 15 "code": "VALIDATION_ERROR", 16 "message": "Invalid email address" 17 } 18}

    Building a REST API with Node.js

    Let's build a real REST API endpoint using Express.js:

    javascript
    1const express = require('express'); 2const app = express(); 3app.use(express.json()); // Parse JSON request bodies 4 5// In-memory database array 6let users = [{ id: 1, name: "Alex Chen" }]; 7 8// GET /api/v1/users - List all users 9app.get('/api/v1/users', (req, res) => { 10 res.json({ success: true, data: users }); 11}); 12 13// POST /api/v1/users - Create a user 14app.post('/api/v1/users', (req, res) => { 15 const { name } = req.body; 16 17 if (!name) { 18 return res.status(422).json({ 19 success: false, 20 error: { message: 'Name is required' } 21 }); 22 } 23 24 const newUser = { id: 2, name }; 25 users.push(newUser); 26 res.status(201).json({ success: true, data: newUser }); 27}); 28 29app.listen(3000, () => console.log('API running on http://localhost:3000'));

    Authentication & Security

    You wouldn't want just anyone to be able to delete users from your database. Authentication verifies who is making the request. The global standard for API auth is the JSON Web Token (JWT).

    Client applications attach the token to the HTTP headers of their requests:

    text
    1Authorization: Bearer <your_jwt_token_here>

    Security Best Practice

    Never store sensitive environment variables or JWT Secret Keys in your source code repository. Always use a `.env` file that is ignored by Git.


      API Testing & Debugging

      Testing APIs without a tool is painful. You can use command-line tools like curl or desktop apps like Postman to hit endpoints and view the formatted JSON responses.

      bash
      1# Example: Sending a POST request with curl 2curl -X POST http://localhost:3000/api/v1/users \ 3 -H "Content-Type: application/json" \ 4 -d '{"name": "TopicTrick User"}'

      Frequently Asked Questions

      What's the difference between REST and GraphQL?

      REST uses multiple endpoints (one per resource). GraphQL uses a single endpoint where clients specify exactly what data fields they need. REST is simpler and better for cacheing. GraphQL is more flexible for complex data fetching.

      How do I handle API versioning?

      Use URL versioning (/api/v1/, /api/v2/). Maintain older versions for at least 6-12 months with deprecation warnings to give developers time to migrate.

      Should my API use cookie-based or token-based auth?

      For APIs consumed by mobile apps or third parties, JWT (token-based) auth is preferred because it is stateless and cross-domain. For browser-only apps, secure HTTP-only cookies are generally safer from cross-site scripting (XSS).