Snippets Collections
import 'package:flutter/material.dart';
import 'package:shalestin/Screens/home.dart';
  
  void main() => runApp(const MyApp());
  
  class MyApp extends StatelessWidget {
    const MyApp({super.key});
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
 routes: {
        'Home': (context) => const Home(),
      },
        initialRoute: 'Home',
        debugShowCheckedModeBanner: false,

      );
    }
  }
import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService<T> {
  final String _baseUrl;

  ApiService(this._baseUrl);

  Future<List<T>> getAll(T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse(_baseUrl));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to load data');
    }
  }

  Future<List<T>> search(String query, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse('$_baseUrl?search=$query'));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to search data');
    }
  }

  Future<T> create(Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.post(
      Uri.parse(_baseUrl),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 201) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to create data');
    }
  }

  Future<T> update(int id, Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.put(
      Uri.parse('$_baseUrl/$id'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 200) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to update data');
    }
  }

  Future<void> delete(int id) async {
    final response = await http.delete(Uri.parse('$_baseUrl/$id'));
    if (response.statusCode != 204) {
      throw Exception('Failed to delete data');
    }
  }
}
//=============================================
class Note {
  final int id;
  final String title;
  final String content;

  Note({required this.id, required this.title, required this.content});

  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'],
      title: json['title'],
      content: json['content'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
    };
  }
}

final notesService = ApiService<Note>('http://10.0.2.2:8000/api/notes');

// Get all notes
final notes = await notesService.getAll(Note.fromJson);

// Search for notes
final searchResults = await notesService.search('keyword', Note.fromJson);

// Create a new note
final newNote = await notesService.create(
  {
    'title': 'New Note',
    'content': 'This is a new note',
  },
  Note.fromJson,
);

// Update a note
final updatedNote = await notesService.update(
  newNote.id,
  {
    'title': 'Updated Note',
    'content': 'This is an updated note',
  },
  Note.fromJson,
);

// Delete a note
await notesService.delete(updatedNote.id);
httpClient() {
    curl --silent \
    	# everything in between
         --write-out "\n%{http_code}"
}

response=`httpClient #args #args .....`

http_code=`tail -n1 <<< "$response"`
body=`sed '$ d' <<< "$response"`
var open = window.XMLHttpRequest.prototype.open,
  send = window.XMLHttpRequest.prototype.send;
function openReplacement(method, url, async, user, password) {
  this._url = url;
  return open.apply(this, arguments);
}
function sendReplacement(data) {
  if(this.onreadystatechange) {
    this._onreadystatechange = this.onreadystatechange;
  }
  /**
   * PLACE HERE YOUR CODE WHEN REQUEST IS SENT  
   */
  this.onreadystatechange = onReadyStateChangeReplacement;
  return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
  /**
   * PLACE HERE YOUR CODE FOR READYSTATECHANGE
   */
  if(this._onreadystatechange) {
    return this._onreadystatechange.apply(this, arguments);
  }
}
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;

// https://dmitripavlutin.com/catch-the-xmlhttp-request-in-plain-javascript/
HTTP defines a bunch of meaningful status codes that can be returned from your API. These can be leveraged to help the API consumers route their responses accordingly. I've curated a short list of the ones that you definitely should be using:

200 OK - Response to a successful GET, PUT, PATCH or DELETE. Can also be used for a POST that doesn't result in a creation.
201 Created - Response to a POST that results in a creation. Should be combined with a Location header pointing to the location of the new resource
204 No Content - Response to a successful request that won't be returning a body (like a DELETE request)
304 Not Modified - Used when HTTP caching headers are in play
400 Bad Request - The request is malformed, such as if the body does not parse
401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser
403 Forbidden - When authentication succeeded but authenticated user doesn't have access to the resource
404 Not Found - When a non-existent resource is requested
405 Method Not Allowed - When an HTTP method is being requested that isn't allowed for the authenticated user
410 Gone - Indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions
415 Unsupported Media Type - If incorrect content type was provided as part of the request
422 Unprocessable Entity - Used for validation errors
429 Too Many Requests - When a request is rejected due to rate limiting
Options +Indexes
IndexOptions FancyIndexing
IndexIgnore README .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>
const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// Examples
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
star

Sat Jul 13 2024 11:08:00 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http
star

Wed Jun 19 2024 08:07:51 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http
star

Tue Jan 24 2023 09:43:45 GMT+0000 (Coordinated Universal Time)

#bash #sh #shell #curl #http
star

Tue Dec 07 2021 15:52:16 GMT+0000 (Coordinated Universal Time) https://dmitripavlutin.com/catch-the-xmlhttp-request-in-plain-javascript/

#http
star

Mon Jun 28 2021 15:52:32 GMT+0000 (Coordinated Universal Time)

#http
star

Mon Jun 07 2021 16:07:55 GMT+0000 (Coordinated Universal Time)

#htaccess #webserver #http
star

Fri May 28 2021 11:05:45 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/4083233

#htaccess #webserver #http
star

Wed Nov 04 2020 08:47:54 GMT+0000 (Coordinated Universal Time) https://medium.com/swlh/24-modern-es6-code-snippets-to-solve-practical-js-problems-3609f301859e

#javascript #http #get #url

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension