DeveloperBreeze

Various cURL Examples for API Interactions

# Update resource with PUT request
curl -X PUT https://api.example.com/resource/123 \
    -H 'Content-Type: application/json' \
    -d '{"key": "updated_value"}'

# Retrieve data with GET request
curl https://api.example.com/data

# Send data with POST request to a form endpoint
curl -X POST https://api.example.com/form-endpoint \
    -d 'param1=value1&param2=value2'

# Delete resource with DELETE request and Authorization header
curl -X DELETE https://api.example.com/resource/456 \
    -H 'Authorization: Bearer your_access_token'

# Upload a file with POST request to an upload endpoint
curl -X POST https://api.example.com/upload-endpoint \
    -H 'Content-Type: multipart/form-data' \
    -F 'file=@/path/to/your/file.txt'

# Send JSON data with POST request to a secured endpoint with headers and authorization
curl -X POST https://api.example.com/post-endpoint \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer your_access_token' \
    -d '{"username": "john_doe", "password": "secretpassword"}'

# Send JSON data with POST request to an endpoint with cookies
curl -X POST https://example.com/api/endpoint \
    -H 'Content-Type: application/json' \
    -H 'Cookie: sessionid=your_session_id' \
    -d '{"key1": "value1", "key2": "value2"}'

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

You should use Etherscan when you need to read data from the Ethereum blockchain, such as querying transaction details, wallet balances, or token transfers. Etherscan is a powerful tool for building blockchain explorers or applications that focus on data analytics.

const axios = require('axios');

// Replace with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';

// Replace with the Ethereum address you want to query
const address = '0xYourEthereumAddress';

// Etherscan API URL to fetch wallet balance
const url = `https://api.etherscan.io/api?module=account&action=balance&address=${address}&tag=latest&apikey=${apiKey}`;

async function getWalletBalance() {
  try {
    const response = await axios.get(url);
    const balanceInWei = response.data.result;

    // Convert balance from Wei to Ether
    const balanceInEther = balanceInWei / 1e18;
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
  } catch (error) {
    console.error('Error fetching balance:', error);
  }
}

getWalletBalance();

Oct 24, 2024
Read More
Tutorial
php

بناء API متقدم باستخدام Laravel Passport للتوثيق

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    // تسجيل مستخدم جديد
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $token = $user->createToken('LaravelPassportAPI')->accessToken;

        return response()->json(['token' => $token], 201);
    }

    // تسجيل الدخول
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            $token = $user->createToken('LaravelPassportAPI')->accessToken;

            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }
    }

    // الحصول على بيانات المستخدم
    public function user()
    {
        return response()->json(Auth::user(), 200);
    }
}

افتح ملف routes/api.php وأضف المسارات الخاصة بالتسجيل وتسجيل الدخول:

Sep 27, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        console.log("الاسم:", data.name);
    })
    .catch(error => {
        console.error("حدث خطأ:", error);
    });

في هذا المثال، نستخدم fetch() لطلب بيانات من API، ثم نستخدم response.json() لتحويل الاستجابة إلى كائن JSON يمكننا التعامل معه.

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

In this guide, we've covered the basics of AJAX, focusing on how to make requests using both XMLHttpRequest and the modern Fetch API. AJAX allows you to create more dynamic and responsive web applications by enabling seamless communication between the client and server without reloading the entire page.

By mastering AJAX with JavaScript, you'll be able to implement interactive features like real-time updates, live data fetching, and much more in your web applications.

Sep 18, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'New Post',
    body: 'This is the content of the new post.',
    userId: 1
  })
  .then(response => {
    console.log('Post created:', response.data);
  })
  .catch(error => {
    console.error('Error creating post:', error);
  });
  • We use axios.post() to send a POST request to the API endpoint.
  • The second argument to axios.post() is the data object that will be sent with the request.

Sep 02, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

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.

Aug 24, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

In vite.config.js, set up Vite to work with React:

   import { defineConfig } from 'vite';
   import laravel from 'laravel-vite-plugin';
   import react from '@vitejs/plugin-react';

   export default defineConfig({
       plugins: [
           laravel({
               input: ['resources/css/app.css', 'resources/js/app.jsx'],
               refresh: true,
           }),
           react(),
       ],
   });

Aug 14, 2024
Read More
Tutorial
python

Advanced Pybit Tutorial: Managing Leverage, Stop-Loss Orders, Webhooks, and More

Managing open orders and closing positions is essential for effective trading. Pybit makes it straightforward to close orders.

Use the following function to close an open order:

Aug 14, 2024
Read More
Tutorial
python

A Beginner's Guide to Pybit: Interacting with the Bybit API

First, you'll need to install the Pybit package. You can do this using pip:

pip install pybit

Aug 14, 2024
Read More
Tutorial
php

Integrating and Using NMI Payment Gateway in Laravel

This method uses the customer’s vault ID to process a payment for the specified amount. It handles test mode and logs the payment response using Laravel’s info logging.

Now that the service is set up, you can use it in your Laravel controllers or services.

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

func getBooks(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(books)
}

Add the getBook function to main.go:

Aug 12, 2024
Read More
Code
javascript json

How to Deep Clone a JavaScript Object

No preview available for this content.

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
Code
javascript json

JavaScript Code Snippet: Fetch and Display Data from an API

No preview available for this content.

Aug 04, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

mkdir flask_rest_api
cd flask_rest_api
python -m venv venv

Aug 03, 2024
Read More
Code
php

File Upload with Type Validation in PHP

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Fetch JSON Data from API in JavaScript

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

JavaScript File Upload using Fetch API and FormData

No preview available for this content.

Jan 26, 2024
Read More
Code
python

JSON Serialization and Deserialization

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Upload and Store File in Laravel

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!