Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v1 #46

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

v1 #46

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions source/helloWorldWebApi/AppDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore;
using helloWorld.Model;

public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}

public DbSet<HelloWorld> HelloWorlds { get; set; }


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);


}
}
92 changes: 92 additions & 0 deletions source/helloWorldWebApi/Controllers/HelloWorldController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using helloWorld.Model;

namespace helloWorld.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelloWorldController : ControllerBase
{
private readonly AppDbContext _context;

public HelloWorldController(AppDbContext context)
{
_context = context;
}

// Récupérer toutes les entrées HelloWorld
[HttpGet(Name = "GetHelloWorlds")]
public async Task<IEnumerable<HelloWorld>> Get()
{
return await _context.HelloWorlds.ToListAsync(); // Corrigé à HelloWorlds
}

// Récupérer un HelloWorld par ID
[HttpGet("{id}")]
public async Task<IActionResult> GetHelloWorldById(int id)
{
var helloWorld = await _context.HelloWorlds.FindAsync(id); // Corrigé à HelloWorlds
if (helloWorld == null)
{
return NotFound($"HelloWorld with ID {id} not found.");
}
return Ok(helloWorld);
}

// Ajouter une nouvelle entrée HelloWorld
[HttpPost]
public async Task<IActionResult> PostHelloWorld([FromBody] HelloWorld helloWorld)
{
if (helloWorld == null)
{
return BadRequest("HelloWorld data is null.");
}

_context.HelloWorlds.Add(helloWorld); // Corrigé à HelloWorlds
await _context.SaveChangesAsync();
return Ok(helloWorld);
}

// Mettre à jour une entrée HelloWorld existante
[HttpPut("{id}")]
public async Task<IActionResult> UpdateHelloWorld(int id, [FromBody] HelloWorld updatedHelloWorld) // Corrigé de Comptable à HelloWorld
{
if (id != updatedHelloWorld.Id)
{
return BadRequest("HelloWorld ID mismatch.");
}

var helloWorld = await _context.HelloWorlds.FindAsync(id); // Corrigé de CelloWorlds à HelloWorlds
if (helloWorld == null)
{
return NotFound("HelloWorld not found.");
}

// Mise à jour des propriétés de l'objet HelloWorld
helloWorld.Name = updatedHelloWorld.Name;


_context.Entry(helloWorld).State = EntityState.Modified;
await _context.SaveChangesAsync();

return Ok(helloWorld);
}

// Supprimer une entrée HelloWorld
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteHelloWorld(int id) // Corrigé de Comptable à HelloWorld
{
var helloWorld = await _context.HelloWorlds.FindAsync(id); // Corrigé de HelloWorldS à HelloWorlds
if (helloWorld == null)
{
return NotFound("HelloWorld not found.");
}

_context.HelloWorlds.Remove(helloWorld); // Corrigé de HelloWorldS à HelloWorlds
await _context.SaveChangesAsync();

return Ok($"HelloWorld entry with ID {id} deleted.");
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace helloWorldWebApi.Migrations
{
/// <inheritdoc />
public partial class initialCreated : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySql:CharSet", "utf8mb4");

migrationBuilder.CreateTable(
name: "HelloWorlds",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_HelloWorlds", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "HelloWorlds");
}
}
}
42 changes: 42 additions & 0 deletions source/helloWorldWebApi/Migrations/AppDbContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

#nullable disable

namespace helloWorldWebApi.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 64);

MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder);

modelBuilder.Entity("helloWorld.Model.HelloWorld", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");

MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<int>("Id"));

b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");

b.HasKey("Id");

b.ToTable("HelloWorlds");
});
#pragma warning restore 612, 618
}
}
}
11 changes: 11 additions & 0 deletions source/helloWorldWebApi/Model/HelloWorld.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace helloWorld.Model
{
public class HelloWorld
{
public int Id { get; set; }
public string Name { get; set; }

}
}
30 changes: 30 additions & 0 deletions source/helloWorldWebApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using helloWorld;

var builder = WebApplication.CreateBuilder(args);

// Définir la chaîne de connexion (à adapter selon vos besoins)
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

// Ajouter le service DbContext avec la chaîne de connexion pour MySQL
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
41 changes: 41 additions & 0 deletions source/helloWorldWebApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:29548",
"sslPort": 44392
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5125",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7093;http://localhost:5125",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
51 changes: 51 additions & 0 deletions source/helloWorldWebApi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# HelloWorld API Project

## Introduction

This project is a simple API built with ASP.NET Core. It allows you to manage entries of type `HelloWorld`. Each entry has an identifier (`Id`) and a name (`Name`). This API uses Entity Framework Core to interact with a database.

## Migration Instructions

To add an initial migration and update the database, run the following commands in the terminal at the root of your project:

```bash
dotnet ef migrations add InitialCreate
dotnet ef database update
```
![alt text](image.png)

## JSON Request Examples

Here are some examples of JSON requests that you can use to interact with the API:

### Retrieve all HelloWorld entries
- **Method**: GET
- **URL**: /HelloWorld

### Retrieve a HelloWorld entry by ID
- **Method**: GET
- **URL**: /HelloWorld/{id}

### Add a new HelloWorld entry
- **Method**: POST
- **URL**: /HelloWorld
- **Request Body**:
```json
{
"Name": "Example HelloWorld"
}

Update a HelloWorld entry
Method: PUT
URL: /HelloWorld/{id}
Request Body:
{
"Id": 1,
"Name": "Updated HelloWorld"
}

Delete a HelloWorld entry
Method: DELETE
URL: /HelloWorld/{id}
Conclusion
This project provides a basic API for managing HelloWorld entries. You can extend this API by adding additional features according to your needs.
8 changes: 8 additions & 0 deletions source/helloWorldWebApi/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Loading