Build networking layer with URLSession and Codable
✓Works with OpenClaudeYou are a Swift networking engineer. The user wants to build a robust networking layer using URLSession and Codable to handle API requests, responses, and error handling.
What to check first
- Verify your project target supports iOS 13+ (URLSession Codable support requires this minimum)
- Check that your data models conform to
Codableprotocol with properCodingKeysif property names differ from JSON keys - Confirm your app has the necessary
NSBonjourServicesor network permissions inInfo.plistfor your target endpoints
Steps
- Create an enum to define all API endpoints with associated values for parameters—use
URLComponentsto build URLs dynamically with query items - Define a generic
APIRequest<T>struct that wraps the endpoint, HTTP method, headers, and body encoding logic - Create custom
Codablemodels for your response types—use@CodingKeysto map snake_case JSON to camelCase Swift properties - Build a
NetworkManagerclass that creates a URLSession instance with a custom URLSessionConfiguration for timeouts and cache policies - Implement a generic
fetch<T: Decodable>()method that accepts anAPIRequest<T>, constructs aURLRequest, and handles the data task - Add comprehensive error handling—distinguish between network errors, HTTP status codes (400, 401, 500), and JSON decoding failures
- Use
JSONDecoderwith a customdateDecodingStrategyif your API returns timestamps in ISO8601 or Unix timestamp format - Add retry logic for transient failures (timeouts, 503 Service Unavailable) with exponential backoff using
DispatchTime
Code
import Foundation
// MARK: - API Endpoint Definition
enum APIEndpoint {
case getUser(id: String)
case listPosts(page: Int)
case createPost(title: String, body: String)
var baseURL: URL {
URL(string: "https://jsonplaceholder.typicode.com")!
}
var path: String {
switch self {
case .getUser(let id):
return "/users/\(id)"
case .listPosts:
return "/posts"
case .createPost:
return "/posts"
}
}
var httpMethod: String {
switch self {
case .createPost:
return "POST"
default:
return "GET"
}
}
var queryItems: [URLQueryItem]? {
switch self {
case .listPosts(let page):
return [URLQueryItem(name: "page", value: String(page))]
default:
return nil
}
}
var body: Encodable? {
switch self {
case .createPost(let title, let body):
return PostRequest(title: title, body: body
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Swift / iOS Skills
Other Claude Code skills in the same category — free to download.
SwiftUI
Build SwiftUI views with state management and navigation
UIKit
Create UIKit view controllers with Auto Layout
Core Data
Set up Core Data with models, contexts, and fetch requests
Swift Combine
Use Combine for reactive programming in Swift
Swift Testing
Write XCTest unit and UI tests for iOS apps
Swift Async/Await Concurrency
Use Swift's structured concurrency for async code without callback hell
Swift CoreData Relationships
Model one-to-many and many-to-many relationships in CoreData
Want a Swift / iOS skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.