Skip to main content
Sproutern LogoSproutern
InterviewsGamesBlogToolsAbout
Sproutern LogoSproutern
Donate
Sproutern LogoSproutern

Your complete education and career platform. Access real interview experiences, free tools, and comprehensive resources to succeed in your professional journey.

Company

About UsContact UsSuccess StoriesHire Me / ServicesOur MethodologyBlog❤️ Donate

For Students

Find InternshipsScholarshipsCompany ReviewsCareer ToolsFree ResourcesCollege PlacementsSalary Guide

🌍 Study Abroad

Country Guides🇩🇪 Study in Germany🇺🇸 Study in USA🇬🇧 Study in UK🇨🇦 Study in CanadaGPA Converter

Resources

Resume TemplatesCover Letter SamplesInterview Cheat SheetLinkedIn OptimizationSalary NegotiationGitHub Profile GuideATS Resume KeywordsResume CheckerCGPA ConverterIT CertificationsDSA RoadmapInterview QuestionsFAQ

Legal

Privacy PolicyTerms & ConditionsCookie PolicyDisclaimerSitemap Support

© 2026 Sproutern. All rights reserved.

•

Made with ❤️ for students worldwide

Follow Us:
    Explore More
    🛠️Free Career Tools💼Interview Experiences🗺️Career Roadmaps
    Keep reading

    Move from advice to action

    Use supporting tools and destination pages to turn an article into a concrete next step.

    Interview Prep Hub

    Prep

    Practice frameworks, question banks, and checklists in one place.

    Open page

    Resume Score Checker

    Tool

    Test whether your resume matches the role you want.

    Open page

    Company Guides

    Research

    Review hiring patterns, salary ranges, and work culture.

    Open page

    Interview Experiences

    Stories

    Read real candidate stories before your next round.

    Open page
    Popular with students
    CGPA ConverterSalary CalculatorResume Score CheckerInterview Prep HubStudy in USA Guide
    Article review
    Human reviewed
    Source-backed

    How Sproutern reviews career articles

    Our blog is written for students, freshers, and early-career professionals. We aim for useful, readable guidance first, but we still expect articles to cite primary regulations, university guidance, or employer-side evidence wherever the advice depends on facts rather than opinion.

    Written by

    Premkumar M

    Founder, editor, and product lead at Sproutern

    View author profile

    Reviewed by

    Sproutern Editorial Team

    Career editors and quality reviewers working from our public editorial policy

    Review standards

    Last reviewed

    March 6, 2026

    Freshness checks are recorded on pages where the update is material to the reader.

    Update cadence

    Evergreen articles are reviewed at least quarterly; time-sensitive posts move sooner

    Time-sensitive topics move faster when rules, deadlines, or market signals change.

    How this content is built and maintained

    We publish articles only after checking whether the advice depends on a policy, a market signal, or first-hand experience. If a section depends on an official rule, we look for the original source. If it depends on experience, we label it as practical guidance instead of hard fact.

    • We do not treat AI-generated drafts as final content; human editors review and rewrite before publication.
    • If an article cites a hiring trend or academic rule, the editorial team looks for the original report, regulation, or handbook first.
    • Major updates are logged so readers can see whether a change reflects a new policy, fresher data, or a corrected explanation.
    Read our methodologyEditorial guidelinesReport a correction

    Primary sources and expert references

    Not every article uses the same dataset, but the editorial expectation is consistent: cite the primary rule, employer guidance, or research owner wherever it materially affects the reader.

    • Primary regulations, employer documentation, and university sources

      Blog articles are expected to cite the original policy, handbook, or employer guidance before we publish practical takeaways.

    • OECD and World Economic Forum

      Used for labor-market, education, and future-of-work context when broader data is needed.

    • NACE and public recruiter guidance

      Used for resume, interview, internship, and early-career hiring patterns where employer-side evidence matters.

    Recent updates

    March 6, 2026

    Added reviewer and methodology disclosure to major blog surfaces

    The blog section now clearly shows review context, source expectations, and correction workflow alongside major article experiences.

    Reader feedback loop

    Writers and editors monitor feedback for factual issues, unclear advice, and stale references that should be refreshed.

    Prefer the full policy pages? Read our public standards or contact the team if a major page needs a correction.Open standards
    Back to Blog
    Loading TOC...
    Programming

    REST API Tutorial for Beginners

    Sproutern Career TeamLast Updated: 2026-01-0620 min read
    Reviewed by Sproutern Editorial TeamEditorial standardsMethodology

    Learn REST API fundamentals from scratch. Understand HTTP methods, status codes, authentication, and how to design, consume, and build RESTful APIs step by step.

    REST API Tutorial for Beginners

    APIs power the modern internet. Every time you use a mobile app, check the weather, or make an online payment, you're interacting with APIs. Understanding APIs is essential for any developer, and REST is the most common API architecture.

    This comprehensive tutorial explains REST APIs from scratch—what they are, how they work, and how to build and consume them.


    What is an API?

    Definition

    API (Application Programming Interface) is a way for different software applications to communicate with each other. It defines the rules and protocols for how applications request and exchange data.

    Real-World Analogy: Think of a restaurant:

    • You (client) → make a request (order from menu)
    • Waiter (API) → takes your request to the kitchen
    • Kitchen (server) → prepares the food
    • Waiter (API) → brings the response (food)

    You don't need to know how the kitchen works—the waiter handles the communication.

    Why APIs Matter

    Use CaseExample
    Mobile appsApp fetches data from server
    Third-party integrationLogin with Google
    MicroservicesServices communicate
    AutomationScripts interact with systems
    Data sharingWeather data for websites

    What is REST?

    Definition

    REST (Representational State Transfer) is an architectural style for designing networked applications. It's not a protocol or standard—it's a set of constraints and principles.

    REST Principles

    PrincipleExplanation
    StatelessEach request contains all info needed; no server-side sessions
    Client-ServerSeparation of concerns; client and server evolve independently
    Uniform InterfaceStandard way to interact with resources
    CacheableResponses can be cached for performance
    Layered SystemClient doesn't know if it's connected to end server or intermediary

    What is a RESTful API?

    A RESTful API is an API that follows REST principles. It uses:

    • Standard HTTP methods
    • URLs to identify resources
    • JSON or XML for data exchange
    • HTTP status codes for response status

    HTTP Fundamentals

    HTTP Methods (Verbs)

    REST APIs use HTTP methods to indicate the action:

    MethodActionExample
    GETRetrieve dataGet all users
    POSTCreate new dataCreate a new user
    PUTUpdate/replace dataUpdate user completely
    PATCHPartial updateUpdate user's email only
    DELETERemove dataDelete a user

    CRUD Operations

    CRUDHTTP MethodExample
    CreatePOSTPOST /users
    ReadGETGET /users or GET /users/123
    UpdatePUT/PATCHPUT /users/123
    DeleteDELETEDELETE /users/123

    HTTP Status Codes

    Code RangeCategoryCommon Codes
    1xxInformational100 Continue
    2xxSuccess200 OK, 201 Created, 204 No Content
    3xxRedirection301 Moved, 304 Not Modified
    4xxClient Error400 Bad Request, 401 Unauthorized, 404 Not Found
    5xxServer Error500 Internal Error, 503 Service Unavailable

    Common Status Codes:

    CodeMeaningWhen Used
    200OKSuccessful GET, PUT
    201CreatedSuccessful POST (new resource)
    204No ContentSuccessful DELETE
    400Bad RequestInvalid request data
    401UnauthorizedAuthentication required
    403ForbiddenNot allowed even with auth
    404Not FoundResource doesn't exist
    500Server ErrorSomething broke on server

    REST API Structure

    URL Structure (Endpoints)

    RESTful URLs are resource-based:

    https://api.example.com/v1/users/123/orders
    

    Breakdown:

    • https:// - Protocol
    • api.example.com - Domain
    • /v1 - API version
    • /users - Resource (collection)
    • /123 - Resource ID (specific user)
    • /orders - Sub-resource (user's orders)

    Naming Conventions

    Good ✓Bad ✗
    /users/getUsers
    /users/123/user?id=123
    /users/123/orders/getUserOrders
    /products/product-list

    Rules:

    • Use nouns, not verbs
    • Use plural names for collections
    • Use lowercase
    • Use hyphens for multi-word (if needed)

    Request Structure

    GET Request (Retrieve):

    GET /api/users/123 HTTP/1.1
    Host: api.example.com
    Authorization: Bearer <token>
    Accept: application/json
    

    POST Request (Create):

    POST /api/users HTTP/1.1
    Host: api.example.com
    Content-Type: application/json
    Authorization: Bearer <token>
    
    {
        "name": "John Doe",
        "email": "john@example.com",
        "age": 25
    }
    

    Response Structure

    Success Response:

    {
      "status": "success",
      "data": {
        "id": 123,
        "name": "John Doe",
        "email": "john@example.com",
        "age": 25,
        "created_at": "2024-01-15T10:30:00Z"
      }
    }
    

    Error Response:

    {
      "status": "error",
      "message": "User not found",
      "code": "USER_NOT_FOUND"
    }
    

    Data Formats

    JSON (JavaScript Object Notation)

    Most common format for REST APIs:

    {
      "id": 1,
      "name": "John Doe",
      "email": "john@example.com",
      "roles": ["user", "admin"],
      "profile": {
        "bio": "Developer",
        "location": "India"
      },
      "active": true
    }
    

    JSON Data Types: | Type | Example | |------|---------| | String | "hello" | | Number | 42, 3.14 | | Boolean | true, false | | Null | null | | Array | [1, 2, 3] | | Object | {"key": "value"} |

    Headers

    Common HTTP headers:

    HeaderPurposeExample
    Content-TypeFormat of request bodyapplication/json
    AcceptExpected response formatapplication/json
    AuthorizationAuthenticationBearer token123
    Cache-ControlCaching behaviorno-cache

    Consuming REST APIs

    Using JavaScript (Fetch)

    GET Request:

    fetch('https://api.example.com/users')
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((error) => console.error('Error:', error));
    

    With async/await:

    async function getUsers() {
      try {
        const response = await fetch('https://api.example.com/users');
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error('Error:', error);
      }
    }
    

    POST Request:

    async function createUser(userData) {
      const response = await fetch('https://api.example.com/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Bearer token123',
        },
        body: JSON.stringify(userData),
      });
      return response.json();
    }
    
    // Usage
    createUser({ name: 'John', email: 'john@example.com' });
    

    Using Python (Requests)

    GET Request:

    import requests
    
    response = requests.get('https://api.example.com/users')
    data = response.json()
    print(data)
    

    POST Request:

    import requests
    
    user_data = {
        'name': 'John',
        'email': 'john@example.com'
    }
    
    response = requests.post(
        'https://api.example.com/users',
        json=user_data,
        headers={'Authorization': 'Bearer token123'}
    )
    
    print(response.status_code)
    print(response.json())
    

    Using cURL (Command Line)

    GET:

    curl https://api.example.com/users
    

    POST:

    curl -X POST https://api.example.com/users \
      -H "Content-Type: application/json" \
      -d '{"name": "John", "email": "john@example.com"}'
    

    Building REST APIs

    Example with Node.js (Express)

    Setup:

    npm init -y
    npm install express
    

    Basic API:

    const express = require('express');
    const app = express();
    app.use(express.json());
    
    // In-memory data store
    let users = [
      { id: 1, name: 'John', email: 'john@example.com' },
      { id: 2, name: 'Jane', email: 'jane@example.com' },
    ];
    
    // GET all users
    app.get('/api/users', (req, res) => {
      res.json(users);
    });
    
    // GET single user
    app.get('/api/users/:id', (req, res) => {
      const user = users.find((u) => u.id === parseInt(req.params.id));
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
      res.json(user);
    });
    
    // POST create user
    app.post('/api/users', (req, res) => {
      const user = {
        id: users.length + 1,
        name: req.body.name,
        email: req.body.email,
      };
      users.push(user);
      res.status(201).json(user);
    });
    
    // PUT update user
    app.put('/api/users/:id', (req, res) => {
      const user = users.find((u) => u.id === parseInt(req.params.id));
      if (!user) {
        return res.status(404).json({ message: 'User not found' });
      }
      user.name = req.body.name;
      user.email = req.body.email;
      res.json(user);
    });
    
    // DELETE user
    app.delete('/api/users/:id', (req, res) => {
      const index = users.findIndex((u) => u.id === parseInt(req.params.id));
      if (index === -1) {
        return res.status(404).json({ message: 'User not found' });
      }
      users.splice(index, 1);
      res.status(204).send();
    });
    
    app.listen(3000, () => console.log('Server running on port 3000'));
    

    Example with Python (Flask)

    from flask import Flask, jsonify, request
    
    app = Flask(__name__)
    
    users = [
        {'id': 1, 'name': 'John', 'email': 'john@example.com'},
        {'id': 2, 'name': 'Jane', 'email': 'jane@example.com'}
    ]
    
    @app.route('/api/users', methods=['GET'])
    def get_users():
        return jsonify(users)
    
    @app.route('/api/users/<int:user_id>', methods=['GET'])
    def get_user(user_id):
        user = next((u for u in users if u['id'] == user_id), None)
        if not user:
            return jsonify({'message': 'User not found'}), 404
        return jsonify(user)
    
    @app.route('/api/users', methods=['POST'])
    def create_user():
        user = {
            'id': len(users) + 1,
            'name': request.json['name'],
            'email': request.json['email']
        }
        users.append(user)
        return jsonify(user), 201
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Authentication

    Types of API Authentication

    MethodHow It WorksUse Case
    API KeyStatic key in header/querySimple apps
    Basic AuthBase64-encoded username:passwordSimple, internal
    Bearer TokenToken in Authorization headerCommon for apps
    OAuth 2.0Token-based, refresh tokensThird-party auth
    JWTSelf-contained JSON tokensStateless auth

    API Key Example

    Request:

    GET /api/data HTTP/1.1
    X-API-Key: your-api-key-here
    

    Bearer Token Example

    Request:

    GET /api/users HTTP/1.1
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
    

    JWT (JSON Web Token)

    JWT is a self-contained token with three parts:

    header.payload.signature
    

    Example:

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
    eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9.
    SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
    

    API Design Best Practices

    URL Design

    PracticeGood Example
    Use plural nouns/users, /products
    Nest related resources/users/123/orders
    Use query params for filtering/users?role=admin
    Version your API/v1/users
    Keep URLs simple/orders/123 not /getOrderById?id=123

    Response Design

    {
        "status": "success",
        "data": {
            "users": [...],
            "pagination": {
                "page": 1,
                "per_page": 20,
                "total": 100,
                "total_pages": 5
            }
        }
    }
    

    Error Handling

    {
      "status": "error",
      "code": "VALIDATION_ERROR",
      "message": "Validation failed",
      "errors": [
        {
          "field": "email",
          "message": "Invalid email format"
        }
      ]
    }
    

    Pagination

    Query Parameters:

    GET /api/users?page=2&per_page=20
    

    Response:

    {
        "data": [...],
        "pagination": {
            "page": 2,
            "per_page": 20,
            "total_items": 100,
            "total_pages": 5
        }
    }
    

    Filtering and Sorting

    GET /api/products?category=electronics&price_min=1000&sort=price_desc
    

    Testing APIs

    Tools for Testing

    ToolTypeBest For
    PostmanGUIVisual testing, collections
    InsomniaGUIClean interface
    cURLCLIQuick tests, scripting
    Swagger UIWebDocumentation + testing
    HTTPieCLIHuman-friendly cURL alternative

    Postman Usage

    1. Create a new request
    2. Select HTTP method (GET, POST, etc.)
    3. Enter URL
    4. Add headers (if needed)
    5. Add body (for POST/PUT)
    6. Click Send
    7. View response

    Automated Testing

    JavaScript (Jest + Supertest):

    const request = require('supertest');
    const app = require('./app');
    
    describe('Users API', () => {
      it('should get all users', async () => {
        const res = await request(app).get('/api/users');
        expect(res.statusCode).toBe(200);
        expect(res.body).toBeInstanceOf(Array);
      });
    
      it('should create a user', async () => {
        const res = await request(app)
          .post('/api/users')
          .send({ name: 'Test', email: 'test@test.com' });
        expect(res.statusCode).toBe(201);
        expect(res.body.name).toBe('Test');
      });
    });
    

    Common API Examples to Explore

    Public APIs for Practice

    APIPurposeAuth
    JSONPlaceholderFake REST APINone
    GitHub APIGitHub dataOAuth/Token
    OpenWeatherMapWeather dataAPI Key
    REST CountriesCountry infoNone
    PokeAPIPokémon dataNone
    The Movie DBMovie dataAPI Key

    Key Takeaways

    1. REST is an architecture—not a protocol
    2. HTTP methods matter—GET, POST, PUT, DELETE
    3. Status codes communicate—200s success, 400s client error, 500s server error
    4. URLs are resource-based—use nouns, not verbs
    5. JSON is standard—for request and response bodies
    6. Authentication is essential—API keys, tokens, OAuth
    7. Design for developers—clear, consistent, well-documented
    8. Test your APIs—Postman, cURL, automated tests
    9. Version your API—/v1, /v2 for backward compatibility
    10. Practice with public APIs—before building your own

    Frequently Asked Questions

    What's the difference between REST and GraphQL?

    REST uses multiple endpoints for different resources. GraphQL uses one endpoint where clients specify exactly what data they need. REST is simpler; GraphQL is more flexible for complex queries.

    Is REST the same as HTTP?

    No. REST is an architectural style, HTTP is a protocol. REST commonly uses HTTP, but REST principles could theoretically apply to other protocols.

    How do I secure my REST API?

    Use HTTPS, implement authentication (JWT/OAuth), validate inputs, rate limit requests, and use proper authorization for each endpoint.

    What's the difference between PUT and PATCH?

    PUT replaces the entire resource. PATCH updates only specified fields. Use PUT when updating everything, PATCH for partial updates.

    How do I handle API versioning?

    Common methods: URL path (/v1/users), header (Accept-Version: v1), or query param (?version=1). URL path is most common and visible.


    Learning backend development? Explore more resources on Sproutern for programming tutorials, career guidance, and skill development.


    Related Resources on Sproutern

    • AI Resume Optimizer — Get your resume reviewed by AI for free
    • Career Roadmaps — Plan your career path step by step
    • Interview Experiences — Read real stories from candidates
    • Salary Calculator — Compare salaries across companies
    • Typing Speed Test — Test and improve your typing speed

    This article was last reviewed and updated on February 23, 2026. Source: Sproutern Career Research Team.


    Related Resources on Sproutern

    • AI Resume Optimizer
    • Salary Calculator
    • Mock Interview Tool
    • LinkedIn Optimization Guide
    • Salary Negotiation Guide
    S

    Sproutern Career Team

    Our team of career experts, industry professionals, and former recruiters brings decades of combined experience in helping students and freshers launch successful careers.

    Free Resource

    🎯 Free Career Resource Pack

    Get 50+ real interview questions from top MNCs, ATS-optimized resume templates, and a step-by-step placement checklist — delivered to your inbox.

    🔒 No spam. We respect your privacy.

    Share:💬📨🐦💼

    Was this guide helpful?

    Related Articles

    Best Programming Languages to Learn

    Discover the best programming languages to learn for career growth and high-paying tech jobs....

    15 min read

    Data Structures and Algorithms: Complete Roadmap

    Master Data Structures and Algorithms with this complete roadmap. From arrays to dynamic programming...

    25 min read

    Cite This Article

    If you found this article helpful, please cite it as:

    Sproutern Team. "REST API Tutorial for Beginners." Sproutern, 2026-01-06, https://app.sproutern.com/blog/rest-api-tutorial-beginners. Accessed April 10, 2026.