DeveloperBreeze

Python Code Snippet: Simple RESTful API with FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Book(BaseModel):
    title: str
    author: str

# Sample data
books_db = [
    Book(title="The Catcher in the Rye", author="J.D. Salinger"),
    Book(title="To Kill a Mockingbird", author="Harper Lee"),
    Book(title="1984", author="George Orwell")
]

@app.get("/books/", response_model=List[Book])
async def get_books():
    return books_db

@app.post("/books/", response_model=Book)
async def add_book(book: Book):
    books_db.append(book)
    return book

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript python

How to Build a Fullstack App with Flask and React

  • Set up Flask as a backend server.
  • Create RESTful API endpoints in Flask.
  • Fetch and display data in React.
  • Handle form submissions and CRUD operations in React.

This structure can be scaled and modified to fit more complex requirements, such as user authentication, database integration, and more.

Sep 30, 2024
Read More
Tutorial
javascript

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

const invalidJson = '{"name": "أحمد", "age": 30,';  // JSON غير مكتمل

try {
    const person = JSON.parse(invalidJson);
    console.log(person);
} catch (error) {
    console.error("خطأ في تحويل JSON:", error.message);
}

عادة ما تستخدم JSON لجلب البيانات من APIs مثل بيانات الطقس، المستخدمين، أو المنتجات.

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

When a user performs an action on the page, like clicking a button, JavaScript can send a request to a server, receive data, and update the page content without reloading the whole page.

Here’s a basic overview:

Sep 18, 2024
Read More
Tutorial
python

Getting Started with Pydantic: Data Validation and Type Coercion in Python

Pydantic models are simple Python classes that inherit from pydantic.BaseModel. Here's how you can create a basic Pydantic model:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    age: int
    is_active: bool = True

Aug 29, 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
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
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

  venv\Scripts\activate
  • On macOS/Linux:

Aug 03, 2024
Read More
Code
php

JavaScript Promise Example

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
python

JSON Serialization and Deserialization

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Asynchronous Data Fetching in JavaScript using 'fetch'

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Read JSON Data from a File

No preview available for this content.

Jan 26, 2024
Read More
Code
php

JSON File Reading and Decoding

No preview available for this content.

Jan 26, 2024
Read More
Code
bash

Various cURL Examples for API Interactions

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript python

Execute Python Code Using Skulpt

This JavaScript snippet demonstrates how to execute Python code within a browser using Skulpt, a JavaScript implementation of Python. Here's a breakdown of what the code does:

  • Skulpt Configuration:
  • Sk.configure sets up Skulpt with custom functions for output and file reading.
  • output Function: Captures and logs output from the Python code to the browser's console.
  • read Function: Simulates file reading for Skulpt. If <stdin> is requested, it returns predefined Python code. Otherwise, it throws an error indicating the file wasn't found.
  • Defining Python Code:
  • The pythonCode variable contains the Python code to be executed. In this example, it prints two messages:

Jan 26, 2024
Read More
Code
json python

Append Data to JSON File

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!