REST APIs in Python
REST APIs allow different applications to communicate with each other using standard HTTP methods and data formats.
What is REST?
REST stands for Representational State Transfer. It is an architectural style commonly used to design web APIs.
A REST API allows a client application to communicate with a server using HTTP requests.
Simple Definition
A REST API is a web-based interface that allows applications to exchange data using HTTP requests and responses.
REST API Flow
A client sends a request to an API endpoint. The server processes the request and returns a response.
Client
Browser, mobile app or another application sends a request.
REST API
API receives and processes the request.
Response
Server sends data such as JSON back to the client.
Resources in REST APIs
REST APIs usually work with resources. A resource can represent an object or collection of data.
Students
Represents student information.
/students
Courses
Represents available courses.
/courses
Products
Represents product information.
/products
HTTP Methods in REST APIs
REST APIs commonly use HTTP methods to describe the required operation.
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | /students |
| POST | Create new data | /students |
| PUT | Update existing data | /students/1 |
| DELETE | Delete data | /students/1 |
GET Request
GET is commonly used to retrieve data from a server.
from fastapi import FastAPI
app = FastAPI()
@app.get("/students")
def get_students():
return {
"students": [
"Rahul",
"Priya",
"Amit"
]
}
POST Request
POST is commonly used to create new data on the server.
from fastapi import FastAPI
app = FastAPI()
@app.post("/students")
def create_student():
return {
"message": "Student created successfully"
}
PUT Request
PUT is commonly used to update an existing resource.
from fastapi import FastAPI
app = FastAPI()
@app.put("/students/{student_id}")
def update_student(student_id: int):
return {
"message": "Student updated",
"student_id": student_id
}
DELETE Request
DELETE is used to remove a resource.
from fastapi import FastAPI
app = FastAPI()
@app.delete("/students/{student_id}")
def delete_student(student_id: int):
return {
"message": "Student deleted",
"student_id": student_id
}
JSON in REST APIs
JSON is commonly used to exchange structured data between clients and servers.
{
"id": 101,
"name": "Rahul",
"course": "Python",
"city": "Pune"
}
JSON contains data in key-value form and can also contain lists and nested objects.
REST API Endpoints
| Method | Endpoint | Operation |
|---|---|---|
| GET | /students | Get all students |
| GET | /students/1 | Get one student |
| POST | /students | Create a student |
| PUT | /students/1 | Update a student |
| DELETE | /students/1 | Delete a student |
HTTP Status Codes
HTTP status codes tell the client whether a request was successful or whether an error occurred.
200 - OK
The request was successfully processed.
201 - Created
A new resource was successfully created.
400 - Bad Request
The request contains invalid data.
404 - Not Found
The requested resource could not be found.
500 - Server Error
An unexpected server-side error occurred.
Example: Course REST API 🤓👀
The following example creates simple REST endpoints for a training institute.
from fastapi import FastAPI
app = FastAPI()
@app.get("/courses")
def get_courses():
return {
"courses": [
{
"id": 1,
"name": "Python"
},
{
"id": 2,
"name": ".NET Full Stack"
}
]
}
@app.get("/courses/{course_id}")
def get_course(course_id: int):
return {
"course_id": course_id
}
@app.post("/courses")
def create_course():
return {
"message": "Course created"
}
@app.put("/courses/{course_id}")
def update_course(course_id: int):
return {
"message": "Course updated",
"course_id": course_id
}
@app.delete("/courses/{course_id}")
def delete_course(course_id: int):
return {
"message": "Course deleted",
"course_id": course_id
}
Basic REST Principles
Resource Based
APIs should represent resources such as students, courses, or products.
HTTP Methods
HTTP methods define the action performed on the resource.
Stateless
Each request should contain the information required to process it.
Standard Format
JSON is commonly used to exchange API data.
Testing a REST API
REST APIs can be tested using browser tools, API clients, or interactive documentation.
Common Tools
- Browser
- Swagger UI
- Postman
- cURL
Best Practices
- Use clear and meaningful endpoint names.
- Use the correct HTTP method for each operation.
- Return appropriate HTTP status codes.
- Validate incoming data.
- Use consistent JSON response structures.
- Protect sensitive API endpoints.
Common Mistakes
- Using incorrect HTTP methods.
- Creating unclear endpoint names.
- Returning incorrect status codes.
- Not validating client data.
- Mixing unrelated resources in one endpoint.
- Exposing sensitive information in API responses.
Practice Exercise
Create a REST API for students with the following endpoints:
- GET /students → Return all students.
- GET /students/{id} → Return one student.
- POST /students → Create a student.
- PUT /students/{id} → Update a student.
- DELETE /students/{id} → Delete a student.
Test all endpoints using an API testing tool.
Summary
REST APIs allow applications to communicate through HTTP and work with resources such as students and courses. The GET method is used to retrieve data, POST is used to create data, PUT is used to update data, and DELETE is used to remove data. JSON is commonly used for exchanging API data, while HTTP status codes communicate the result of a request.