DeveloperBreeze

Introduction

REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol, usually HTTP. RESTful APIs are widely used due to their simplicity and scalability. This comprehensive cheatsheet covers essential REST API principles and operations, complete with examples presented in HTML tables for easy reference.

1. HTTP Methods

1.1 Basic HTTP Methods

MethodDescriptionExample
GETRetrieve information from the serverGET /users
POSTSubmit data to the serverPOST /users with body { "name": "John" }
PUTUpdate existing data on the serverPUT /users/1 with body { "name": "John" }
DELETEDelete existing data on the serverDELETE /users/1
PATCHPartially update existing data on the serverPATCH /users/1 with body { "name": "John" }

2. Status Codes

2.1 Common HTTP Status Codes

CodeDescriptionExample
200 OKRequest succeededGET /users/1
201 CreatedResource created successfullyPOST /users
204 No ContentRequest succeeded, but no content to returnDELETE /users/1
400 Bad RequestMalformed request syntax or invalid dataPOST /users with invalid JSON
401 UnauthorizedAuthentication is requiredAccessing a protected route without valid token
403 ForbiddenClient is authenticated but does not have permissionTrying to delete a user without admin rights
404 Not FoundRequested resource could not be foundGET /nonexistentresource
500 Internal Server ErrorServer encountered an unexpected conditionServer-side bug or misconfiguration

3. REST Principles

3.1 Stateless

PrincipleDescription
StatelessEach request from a client to a server must contain all information the server needs to fulfill the request. The server must not store any client context between requests.

3.2 Client-Server

PrincipleDescription
Client-ServerThe client and server are separate entities that communicate over a network. The server hosts resources, and the client requests them. This separation improves scalability and simplifies component management.

3.3 Cacheable

PrincipleDescription
CacheableResponses must define themselves as cacheable or non-cacheable to prevent clients from reusing stale or inappropriate data.

4. URL Structure and Endpoints

4.1 URL Components

ComponentDescriptionExample
Base URLThe root URL of the API, typically including the protocol and domainhttps://api.example.com
VersioningIndicates the version of the API being used, often in the URL path/v1/
EndpointThe path to a specific resource or action in the API/users
Query ParametersKey-value pairs appended to the URL to filter or modify the request?page=1&limit=10

4.2 Example URL Structure

ComponentExample
Full URLhttps://api.example.com/v1/users?page=2&limit=10
ExplanationThe URL above requests the second page of the user resource, returning 10 users per page.

5. Authentication

5.1 Authentication Methods

MethodDescriptionExample
API KeyA simple token passed in the request header or query stringGET /users?api_key=YOUR_API_KEY
OAuthStandardized protocol for token-based authorizationOAuth2 with bearer token: Authorization: Bearer YOUR_ACCESS_TOKEN
Basic AuthEncodes username and password into a base64 tokenAuthorization: Basic base64encoded(username:password)

6. Pagination and Filtering

6.1 Pagination

TermDescriptionExample
PaginationDivides the data into manageable chunks, typically using query parameters like page and limit.GET /users?page=1&limit=20

6.2 Filtering

TermDescriptionExample
FilteringAllows you to narrow down the results based on specific criteria, typically using query parameters.GET /users?age=25&gender=male

7. Versioning

7.1 API Versioning

MethodDescriptionExample
URL VersioningInclude the version number in the URL pathhttps://api.example.com/v1/users
Header VersioningSpecify the version in a custom HTTP headerX-API-Version: 1
Accept Header VersioningUse the Accept header to specify the versionAccept: application/vnd.example.v1+json

Conclusion

This REST API cheatsheet provides a comprehensive overview of the most commonly used REST API concepts, complete with examples to help you quickly find the information you need. Whether you're building or consuming APIs, this guide serves as a quick reference to help you work more efficiently with REST APIs.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
php

Building a Custom Pagination System for API Responses

   namespace App\Http\Controllers;

   use App\Models\Post;

   class PostController extends Controller
   {
       public function index()
       {
           $posts = Post::paginate(10); // Default pagination
           return response()->json($posts);
       }
   }

Modify the response structure to include metadata and links:

Nov 16, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

from flask_cors import CORS

app = Flask(__name__)
CORS(app)

This will allow the frontend (running on a different port) to make requests to the backend.

Sep 30, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

Example:

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Sep 02, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

Now, let's implement each of the endpoints.

Add the getBooks function to main.go:

Aug 12, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

  • Fetch Books
  query {
    books {
      title
      author
    }
  }

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

First, create a new directory for your project and initialize it with npm:

   mkdir graphql-server
   cd graphql-server
   npm init -y

Aug 12, 2024
Read More
Code
json python

Python Code Snippet: Simple RESTful API with FastAPI

No preview available for this content.

Aug 04, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

  • Get all items:
  curl http://127.0.0.1:5000/api/items

Aug 03, 2024
Read More
Code
bash

Various cURL Examples for API Interactions

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Simple Server-Side Handling of HTTP Methods

No preview available for this content.

Jan 26, 2024
Read More
Code
php

URL Encoding and Decoding

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Flask Route Configuration with Optional Parameter Handling

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!